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 blkObjs(blkid): blockName = rs.BlockInstanceName(blkid) objref = rs.coercerhinoobject(blkid) idef = objref.InstanceDefinition idefIndex = idef.Index lvl = levels[rs.GetUserText(blkid, 'level')] height = float(lvl['height']) xform = rs.BlockInstanceXform(blkid) objects = rs.BlockObjects(blockName) # masses = map(lambda x: massFromSrf(x, height), objects) # newblk = rs.AddBlock(masses, (0,0,0), name=name, delete_input=True) # objects.extend(masses) newGeometry = [] newAttributes = [] for object in objects: newGeometry.append(rs.coercegeometry(object)) ref = Rhino.DocObjects.ObjRef(object) attr = ref.Object().Attributes attr.SetUserString('blkname', blockName) newAttributes.append(attr) InstanceDefinitionTable = sc.doc.ActiveDoc.InstanceDefinitions InstanceDefinitionTable.ModifyGeometry(idefIndex, newGeometry, newAttributes) # rs.TransformObjects(masses, xform) rs.DeleteObjects(masses)
def SampleSerialization(): # Select baseeobject base_id = rs.GetObject('Select object') base_obj = rs.coercerhinoobject(base_id) # Select object to embed id = rs.GetObject('Select object to embed') geometry = rs.coercegeometry(id) print(geometry) # Convert geometry to bytes bytes = GeometryBaseToBytes(geometry) print(bytes) # Add bytes to base object's dictionary key = 'test' base_obj.Attributes.UserDictionary.Set.Overloads[str,IEnumerable[System.Byte]](key ,bytes) # Get bytes from base object new_bytes = base_obj.Attributes.UserDictionary.GetBytes(key) print(new_bytes) # Convert bytes to geometry new_geometry = BytesToGeometryBase(new_bytes) print(new_geometry) # Add geometry to document new_id = sc.doc.Objects.Add(new_geometry) print(new_id) # Remove bytes from dictionary base_obj.Attributes.UserDictionary.Remove(key)
def unionAllCurves(Curves): res = [] for curveCount in range(0, len(Curves), 2): try: sc.doc = rc.RhinoDoc.ActiveDoc #change target document rs.EnableRedraw(False) guid1 = sc.doc.Objects.AddCurve(Curves[curveCount]) guid2 = sc.doc.Objects.AddCurve(Curves[curveCount + 1]) all = rs.CurveBooleanUnion([guid1, guid2]) rs.DeleteObjects(guid1) rs.DeleteObjects(guid2) if all: a = [rs.coercegeometry(a) for a in all] for g in a: g.EnsurePrivateCopy() #must ensure copy if we delete from doc rs.DeleteObjects(all) sc.doc = ghdoc #put back document rs.EnableRedraw() if a == None: a = [Curves[curveCount], Curves[curveCount + 1]] except: rs.DeleteObjects(guid1) sc.doc = ghdoc #put back document rs.EnableRedraw() a = [Curves[curveCount]] if a: res.extend(a) return res
def selectObjperVolume(ids, targetV): volumes = [] objs = [rs.coercegeometry(id) for id in ids] for i, obj in enumerate(objs): if isinstance(obj, Rhino.Geometry.Brep): if obj.IsSolid: volumes.append((rs.SurfaceVolume(obj)[0], ids[i])) elif isinstance(obj, Rhino.Geometry.Extrusion): if obj.IsSolid: volumes.append((rs.SurfaceVolume(obj)[0], ids[i])) elif isinstance(obj, Rhino.Geometry.Mesh): if obj.IsClosed: volumes.append((rs.MeshVolume([obj])[1], ids[i])) if len(volumes) > 0: subtractL = [] for i, v in enumerate(volumes): subtractL.append((abs(v[0] - targetV), v[0], v[1])) subtractL.sort() rs.SelectObject(subtractL[0][2]) print "Selected object with %s %s volume" % (subtractL[0][1], unitSystem()) return subtractL[0][2] else: print "No closed object selected" return None
def selectObjperVolume(ids, targetV): volumes = [] objs = [rs.coercegeometry(id) for id in ids] for i,obj in enumerate(objs): if isinstance(obj, Rhino.Geometry.Brep): if obj.IsSolid: volumes.append((rs.SurfaceVolume(obj)[0],ids[i])) elif isinstance(obj, Rhino.Geometry.Extrusion): if obj.IsSolid: volumes.append((rs.SurfaceVolume(obj)[0],ids[i])) elif isinstance(obj, Rhino.Geometry.Mesh): if obj.IsClosed: volumes.append((rs.MeshVolume([obj])[1],ids[i])) if len(volumes) > 0: subtractL = [] for i,v in enumerate(volumes): subtractL.append((abs(v[0]-targetV),v[0],v[1])) subtractL.sort() rs.SelectObject(subtractL[0][2]) print "Selected object with %s %s volume" % (subtractL[0][1],unitSystem()) return subtractL[0][2] else: print "No closed object selected" return None
def createFromPlaneAndObjectSize(rgPlane, obj_ForSize, bDebug=False): if not isinstance(obj_ForSize, (list, tuple, set)): obj_ForSize = [obj_ForSize] bbox_Use = rg.BoundingBox.Empty plane_to_world = rg.Transform.ChangeBasis(plane0=rgPlane, plane1=rg.Plane.WorldXY) for obj in obj_ForSize: geom = rs.coercegeometry(obj) if isinstance(geom, rg.BrepFace): rgBrep_1Face = geom.DuplicateFace(duplicateMeshes=False) bBoxX = rgBrep_1Face.GetBoundingBox(plane=rgPlane) rgBrep_1Face.Dispose() else: bBoxX = geom.GetBoundingBox(plane=rgPlane) if not bBoxX.IsValid: return bbox_Use.Union(other=bBoxX) bbox_Use.Inflate(10.0 * sc.doc.ModelAbsoluteTolerance) bbox_Use.Transform(xform=plane_to_world) if bDebug: box_Use = rg.Box(bbox_Use) sc.doc.Objects.AddBox(box_Use) sc.doc.Views.Redraw() rgSrf1 = rg.PlaneSurface.CreateThroughBox(plane=rgPlane, box=bbox_Use) return rgSrf1
def get_input_geom(_input_list, _ghenv): """ Gets geom and guid from whatever objects are input as the '_srfcs' """ _input_num = 0 output = [] Geom = namedtuple('Geom', ['geom', 'guid']) for i, input_obj in enumerate(_input_list): if not input_obj: continue input_guid = _ghenv.Component.Params.Input[_input_num].VolatileData[0][ i].ReferenceID rh_obj = Rhino.RhinoDoc.ActiveDoc.Objects.Find(input_guid) if rh_obj: geom = rs.coercegeometry(rh_obj) try: for srfc in geom.Surfaces: output.append(Geom(srfc, input_guid)) except AttributeError as e: output.append(Geom(geom, input_guid)) else: try: for srfc in input_obj.Surfaces: output.append(Geom(srfc, None)) except AttributeError as e: output.append(Geom(input_obj, None)) return output
def calcArea(srf): area = Rhino.Geometry.AreaMassProperties.Compute( rs.coercegeometry(srf)).Area # area = rs.SurfaceArea(srf)[0] totalArea = round(castToM(False, area), 2) totalAreaPy = round(totalArea / 3.3058, 2) return [totalArea, totalAreaPy]
def PVsurfaceInputData(PVsurface): if (PVsurface == None): PVsurfaceInputType = srfArea = None validPVsurfaceData = False printMsg = "Please input Surface (not polysurface) to \"_PVsurface\".\nOr input surface Area in square meters (example: \"100\").\nOr input Nameplate DC power rating in kiloWatts (example: \"4 kw\")." return PVsurfaceInputType, srfArea, validPVsurfaceData, printMsg # check PVsurface input obj = rs.coercegeometry(PVsurface) # input is surface if isinstance(obj,Rhino.Geometry.Brep): PVsurfaceInputType = "brep" facesCount = obj.Faces.Count if facesCount > 1: # inputted polysurface PVsurfaceInputType = srfArea = None validPVsurfaceData = False printMsg = "The brep you supplied to \"_PVsurface\" is a polysurface. Please supply a surface" return PVsurfaceInputType, srfArea, validPVsurfaceData, printMsg else: # inputted brep with a single surface srfArea = Rhino.Geometry.AreaMassProperties.Compute(obj).Area # in m2 validPVsurfaceData = True printMsg = "ok" return PVsurfaceInputType, srfArea, validPVsurfaceData, printMsg else: PVsurfaceInputType = "number" try: # input is number (pv surface area in m2) srfArea = float(PVsurface) # in m2 validPVsurfaceData = True printMsg = "ok" return PVsurfaceInputType, srfArea, validPVsurfaceData, printMsg except Exception, e: pass # input is string (nameplateDCpowerRating in kW) lowerString = PVsurface.lower() if "kw" in lowerString: PVsurfaceInputType = srfArea = None validPVsurfaceData = False printMsg = "\"Tilt and orientation factor\" component does not support the \"kw\" PVsurface inputs. Please input either a Grasshopper/Rhino surface or its area." return PVsurfaceInputType, srfArea, validPVsurfaceData, printMsg else: PVsurfaceInputType = srfArea = None validPVsurfaceData = False printMsg = "Something is wrong with your \"PVsurface\" input data" return PVsurfaceInputType, srfArea, validPVsurfaceData, printMsg
def exportPtCloudDataToPLY(ptCloudIds): # ply file path filePath = rs.SaveFileName("Save ply file", "*.ply||", None, "exportPointCloudData", "ply") if filePath == None: print "You haven't picked a file name for the .ply file" return # merge all picked point clouds ptClouds = [rs.coercegeometry(id) for id in ptCloudIds] joinedPtCloud = Rhino.Geometry.PointCloud() for ptCloud in ptClouds: joinedPtCloud.Merge(ptCloud) file = open(filePath, "w") pts = joinedPtCloud.GetPoints() plyheader = """ply format ascii 1.0 comment Author: point cloud PLY export, by Djordje Spasic obj_info Generated by Rhino 5! element vertex %s property float x property float y property float z property float nx property float ny property float nz property uchar red property uchar green property uchar blue end_header\n""" % len(pts) file.write(plyheader) #default values defaultColor = System.Drawing.Color.FromArgb(0, 0, 0) # black defaultNormal = Rhino.Geometry.Vector3d(0, 0, 1) # z vector if joinedPtCloud.ContainsColors: colors = joinedPtCloud.GetColors() else: colors = [defaultColor for i in range(len(pts))] if joinedPtCloud.ContainsNormals: normals = joinedPtCloud.GetNormals() else: normals = [defaultNormal for i in range(len(pts))] for i in range(len(pts)): line = "%.3f %.3f %.3f %.3f %.3f %.3f %s %s %s\n" % ( pts[i].X, pts[i].Y, pts[i].Z, normals[i].X, normals[i].Y, normals[i].Z, colors[i].R, colors[i].G, colors[i].B) file.write(line) file.close() print "Point cloud data successfully exported to '%s' file." % filePath
def Volumetria(eixos, dist_e, dist_l, pto): plAux = rs.CopyObject(eixos, -eZ * (dist_l)) plAux2 = rs.CopyObject(eixos, eZ * (dist_l)) pl1 = rs.OffsetCurve(plAux, pto, dist_e, eZ) pl1 = rs.coercegeometry(pl1) pl2 = rs.OffsetCurve(plAux, pto, -dist_e, eZ) pl2 = rs.coercegeometry(pl2) pl3 = rs.AddLine(rs.CurveStartPoint(pl1), rs.CurveStartPoint(pl2)) pl4 = rs.AddLine(rs.CurveEndPoint(pl1), rs.CurveEndPoint(pl2)) eixos3D = rs.AddPlanarSrf((pl1, pl3, pl2, pl4)) lin = rs.AddLine(rs.CurveStartPoint(plAux), rs.CurveStartPoint(plAux2)) eixos3D = rs.ExtrudeSurface(eixos3D, lin, True) eixos3D = rs.coercegeometry(eixos3D) return eixos3D
def main(point, sphereCenter, sphereRadius, legendBakePar): # [this is the main function which will calculate the distances from the "point" to the sphere.] # [to do this we need to actually calculate the distances between the "point" and points on a sphere.] # [these points on a sphere can be vertices of a mesh created from that sphere. So we will first create a sphere, and then create a mesh from that sphere.] # [create a sphere:] sphereId = rs.AddSphere(sphereCenter, sphereRadius) sphereBrep = rs.coercegeometry( sphereId ) # ["shpereId" represent and id of a sphere. To get the shpere geometry: we use the "rs.coercegeometry" function:] # [create a mesh from sphereBrep. There is no rhinoscriptsyntax function which converts a brep to a mesh, so we have to use RhinoCommon one instead:] sphereMesh = Rhino.Geometry.Mesh.CreateFromBrep( sphereBrep )[0] # [the "[0]" at the end takes a single mesh, because "Rhino.Geometry.Mesh.CreateFromBrep" returns a list] # [now we calculate the distances between the "point" and "sphereMesh" vertices:] distances = [] meshVertices = sphereMesh.Vertices # [get mesh vertices] for vertex in meshVertices: distance = rs.Distance( point, vertex ) # [rhinoscriptsyntax function to calculate the distance between a "point" and each mesh vertex] distances.append(distance) # deconstruct the "legendBakePar_" input to its parts, so that we can use some of them to color the sphereMesh, for title and legend legendStyle, legendPlane, maxValue, minValue, customColors, numLegendCells, legendFontName, legendFontSize, numDecimals, legendUnit, customTitle, scale, layerName, layerColor, layerCategoryName = gismo_preparation.read_legendBakePar( legendBakePar) # [now we color our mesh, according to the upper "ditances" list:] meshColors = gismo_preparation.numberToColor(distances, customColors, minValue, maxValue) coloredSphereMesh = gismo_geometry.colorMeshVertices( sphereMesh, meshColors) # [that's it! now we can create the "title" and "legend" outputs:] # title titleLabelText = "Distance between a point and a sphere" # [this is the text of the title] title, titleStartPt, titleTextSize = gismo_preparation.createTitle( "mesh", [sphereMesh], [titleLabelText], customTitle, textSize=legendFontSize, fontName=legendFontName) # legend unitConversionFactor, unitSystemLabel = gismo_preparation.checkUnits() legendUnit = unitSystemLabel legend, legendPlane = gismo_geometry.createLegend([sphereMesh], distances, legendBakePar_, legendUnit) return distances, sphereMesh, title, legend
def align_outerEdge_to_Xaxis(building_topSrf_brep): # extract the outer edge crv from top building srf for loop in building_topSrf_brep.Loops: # extract loop as a polyline loopCrv = loop.To3dCurve() loopPolyline_strongBox = clr.StrongBox[Rhino.Geometry.Polyline]() success = loopCrv.TryGetPolyline(loopPolyline_strongBox) polylineControlPts = convertPolyline_to_polylineControlPts( loopPolyline_strongBox) polyline = Rhino.Geometry.Polyline(polylineControlPts) # determine if it is inside or outside loop if (loop.LoopType == Rhino.Geometry.BrepLoopType.Outer): building_topSrf_outerPolyline = polyline.ToNurbsCurve() # explode the top outer edge explodedCrv_ids = rs.ExplodeCurves(building_topSrf_outerPolyline) explodedCrvs = [rs.coercegeometry(id) for id in explodedCrv_ids] # find the edge with the longest edge (in order to align the whole outer edge with that edge being parallel to X axis) explodedCrvs_Length_Index_LL = [] for i, explodedCrv in enumerate(explodedCrvs): explodedCrvs_Length_Index_LL.append([explodedCrv.GetLength(), i]) explodedCrvs_Length_Index_LL.sort() longestEdge_index = explodedCrvs_Length_Index_LL[-1][1] longestEdge = explodedCrvs[longestEdge_index] # calculate the angle between longestEdge and X axis xVec = Rhino.Geometry.Vector3d(1, 0, 0) longestEdge_vec = longestEdge.PointAtEnd - longestEdge.PointAtStart xyPlane = Rhino.Geometry.Plane( Rhino.Geometry.Point3d(0, 0, 0), Rhino.Geometry.Vector3d(0, 0, 1) ) # include XY plane in vector angle method to result in 0 to 360 angles angleR = Rhino.Geometry.Vector3d.VectorAngle(xVec, longestEdge_vec, xyPlane) angleD = math.degrees(angleR) # Rotation(angleRadians: float, rotationAxis: Vector3d, rotationCenter: Point3d) -> Transform rotationAxis = Rhino.Geometry.Vector3d(0, 0, 1) rotationCenter = longestEdge.PointAtStart alignToXaxis_matrix = Rhino.Geometry.Transform.Rotation( -angleR, rotationAxis, rotationCenter) rotate_success = building_topSrf_brep.Transform(alignToXaxis_matrix) unalignToXaxis_matrix = Rhino.Geometry.Transform.Rotation( angleR, rotationAxis, rotationCenter) #rotate_success = building_topSrf_brep.Transform(unalignToXaxis_matrix) return building_topSrf_brep, unalignToXaxis_matrix
def calcAreas(srfs): areas = [] for srf in srfs: # areas.append(rs.SurfaceArea(srf)[0]) areas.append( Rhino.Geometry.AreaMassProperties.Compute( rs.coercegeometry(srf)).Area) # totalArea = round(castToM(False, sum(areas)), 2) # totalAreaPy = round(totalArea/3.3058, 2) totalArea = castToM(False, sum(areas)) totalAreaPy = totalArea / 3.3058 return [round(totalArea, 2), round(totalAreaPy, 2)]
def make_zone(pts, bound): # make_zone: (listof pt), curve -> (listof solid) los = [] # get centroid from boundary curve center_pt = rs.CurveAreaCentroid(bound)[0] # extrude solids from sun path for p in pts: line = rs.AddCurve([center_pt, p], 1) extruded = extrude_solid(p, center_pt, bound) los.append(extruded) # boolean interesect all los_ = map(lambda g: rs.coercegeometry(g), los) return bool_solids(los)
def make_zone(pts, bound): # make_zone: (listof pt), curve -> (listof solid) los = [] # get centroid from boundary curve center_pt = rs.CurveAreaCentroid(bound)[0] # extrude solids from sun path for p in pts: line = rs.AddCurve([center_pt,p],1) extruded = extrude_solid(p,center_pt,bound) los.append(extruded) # boolean interesect all los_ = map(lambda g: rs.coercegeometry(g),los) return bool_solids(los)
def exportPtCloudDataToPLY(ptCloudIds): # ply file path filePath = rs.SaveFileName("Save ply file","*.ply||", None, "exportPointCloudData", "ply") if filePath == None: print "You haven't picked a file name for the .ply file" return # merge all picked point clouds ptClouds = [rs.coercegeometry(id) for id in ptCloudIds] joinedPtCloud = Rhino.Geometry.PointCloud() for ptCloud in ptClouds: joinedPtCloud.Merge(ptCloud) file = open(filePath, "w") pts = joinedPtCloud.GetPoints() plyheader = """ply format ascii 1.0 comment Author: point cloud PLY export, by Djordje Spasic obj_info Generated by Rhino 5! element vertex %s property float x property float y property float z property float nx property float ny property float nz property uchar red property uchar green property uchar blue end_header\n""" % len(pts) file.write(plyheader) #default values defaultColor = System.Drawing.Color.FromArgb(0,0,0) # black defaultNormal = Rhino.Geometry.Vector3d(0,0,1) # z vector if joinedPtCloud.ContainsColors: colors = joinedPtCloud.GetColors() else: colors = [defaultColor for i in range(len(pts))] if joinedPtCloud.ContainsNormals: normals = joinedPtCloud.GetNormals() else: normals = [defaultNormal for i in range(len(pts))] for i in range(len(pts)): line = "%.3f %.3f %.3f %.3f %.3f %.3f %s %s %s\n" %(pts[i].X, pts[i].Y, pts[i].Z, normals[i].X, normals[i].Y, normals[i].Z, colors[i].R, colors[i].G, colors[i].B) file.write(line) file.close() print "Point cloud data successfully exported to '%s' file." % filePath
def RemoveFromBlock(): block = rs.GetObject("Select Block to extract objects from", rs.filter.instance, preselect=True) if not block: return blockName = rs.BlockInstanceName(block) objref = rs.coercerhinoobject(block) idef = objref.InstanceDefinition idefIndex = idef.Index XformBlock = rs.BlockInstanceXform(block) blockObjects = rs.BlockObjects(blockName) blockInstanceObjects = rs.TransformObjects(blockObjects, XformBlock, True) objs = rs.GetObjects("Select Objects to extract from Block", objects=blockInstanceObjects) if not objs: rs.DeleteObjects(blockInstanceObjects) return keep = [] #List to keep in block delete = [] #list to delete from block and add to doc rs.EnableRedraw(False) for object in blockInstanceObjects: if object in objs: delete.append(object) else: keep.append(object) if rs.IsBlockReference(blockName): print "Block is referenced from file; unable to modify block" rs.DeleteObjects(keep) return rs.TransformObjects(keep, rs.XformInverse(XformBlock), False) newGeometry = [] newAttributes = [] for object in keep: newGeometry.append(rs.coercegeometry(object)) ref = Rhino.DocObjects.ObjRef(object) attr = ref.Object().Attributes newAttributes.append(attr) InstanceDefinitionTable = sc.doc.ActiveDoc.InstanceDefinitions InstanceDefinitionTable.ModifyGeometry(idefIndex, newGeometry, newAttributes) rs.DeleteObjects(keep) rs.EnableRedraw(True)
def BlockTxt(block, str = False, cstr = False, boolFlipHeb=True): if not block: return blockName = rs.BlockInstanceName(block) objref = rs.coercerhinoobject(block) idef = objref.InstanceDefinition idefIndex = idef.Index XformBlock = rs.BlockInstanceXform(block) blockObjects = rs.BlockObjects(blockName) txtobjs = False for obj in blockObjects: if rs.IsText(obj): if not str: txtobjs = True elif rs.TextObjectText(obj) == str: txtobjs = True if txtobjs: blockInstanceObjects = rs.TransformObjects(blockObjects, XformBlock, True) keep = [] rs.EnableRedraw(False) for obj in blockInstanceObjects: if rs.IsText(obj): if not str and not cstr: str = rs.TextObjectText(obj) cstr = ConvTxt(str, boolFlipHeb) if not cstr == str: rs.TextObjectText(obj, cstr) keep.append(obj) else: keep.append(obj) rs.TransformObjects(keep, rs.XformInverse(XformBlock), False) newGeometry = [] newAttributes = [] for object in keep: newGeometry.append(rs.coercegeometry(object)) ref = Rhino.DocObjects.ObjRef(object) attr = ref.Object().Attributes newAttributes.append(attr) InstanceDefinitionTable = sc.doc.ActiveDoc.InstanceDefinitions InstanceDefinitionTable.ModifyGeometry(idefIndex, newGeometry, newAttributes) rs.DeleteObjects(keep)
def get_tfa_surface_data_from_Rhino(_guid): geom = rs.coercegeometry(_guid) nm = rs.ObjectName(_guid) params = {} param_keys = rs.GetUserText(_guid) for k in param_keys: params[k] =rs.GetUserText(_guid, k) if 'Object Name' in params.keys(): params['Object Name'] = nm return (geom, params)
def getWindowBasics(_in): with idf2ph_rhDoc(): # Get the Window Geometry geom = rs.coercegeometry(_in) windowSurface = ghc.BoundarySurfaces(geom) # Inset the window just slightly. If any windows touch one another or the zone edges # will failt to create a proper closed Brep. So shink them ever so slightly. Hopefully # not enough to affect the results. windowPerim = ghc.JoinCurves(ghc.DeconstructBrep(windowSurface).edges, preserve=False) try: windowPerim = ghc.OffsetonSrf( windowPerim, 0.004, windowSurface) # 0.4mm so hopefully rounds down except: windowPerim = ghc.OffsetonSrf(windowPerim, -0.004, windowSurface) windowSurface = ghc.BoundarySurfaces(windowPerim) # Pull in the Object Name from Rhino Scene windowName = None try: windowName = rs.ObjectName(_in) except: warning = "Can't get the Window name from Rhino for some reason?\n"\ "If you are passing in Rhino Geometry, double check you have named all the surfaces?\n"\ "If you are passing in Grasshopper geometry though, ignore this message." ghenv.Component.AddRuntimeMessage( ghK.GH_RuntimeMessageLevel.Remark, warning) windowName = windowName if windowName != None else 'Unnamed_Window' windowName = cleanUpName(windowName) # Double check that the surface Normal didn't get flipped c1 = ghc.Area(geom).centroid n1 = rs.SurfaceNormal(geom, c1) c2 = ghc.Area(windowSurface).centroid n2 = rs.SurfaceNormal(windowSurface, c2) normAngleDifference = ghc.Degrees(ghc.Angle(n1, n2).angle) if round(normAngleDifference, 0) != 0: # Flip the surface if it doesn't match the source windowSurface = ghc.Flip(windowSurface).surface return windowName, windowSurface
def polyline_to_points(self, polyline): ########## NEW CODE ########## ### Polyline to Points by RhinoCommon pl = rs.coercegeometry(polyline) new_pl = rg.PolylineCurve.ToPolyline(pl) points = new_pl.ToArray() ########## NEW CODE ########## """ ########## OLD CODE 1 ########## ### Start-Point + CurveDiscontinuity + End-Point points = [] ### Start Point start_pt = rs.CurveStartPoint(polyline) points.append(start_pt) ### Segment Points ### Style : 3 = C2 - Continuous first and second derivative segments = rs.CurveDiscontinuity(polyline, 3) for j in range(len(segments)): points.append(segments[j]) ### End Point end_pt = rs.CurveEndPoint(polyline) points.append(end_pt) ########## OLD CODE 1 ########## """ """ ########## OLD CODE 2 ########## ### Polyline to Points by rhinoscriptsuntax ### https://developer.rhino3d.com/api/RhinoScriptSyntax/#collapse-PolylineVertices points = rs.PolylineVertices(polyline) ########## OLD CODE 2 ########## """ return points
def get_input_geom(_input_list, _ghenv): """Gets geom and guid from whatever objects are input as the '_srfcs' """ _input_num = 0 output = [] Geom = namedtuple('Geom', ['geom', 'guid']) for i, input_obj in enumerate(_input_list): if not input_obj: continue # Get the GUID of the item being input into the component's 0-pos input input_guid = _ghenv.Component.Params.Input[_input_num].VolatileData[0][ i].ReferenceID rh_obj = Rhino.RhinoDoc.ActiveDoc.Objects.Find(input_guid) if rh_obj: # Must be some Rhino Geometry being input # Try and explode any multi-surface Breps # If that fails, must be a Mesh, just pass along without exploding. geom = rs.coercegeometry(rh_obj) # Try and convert whatever it is into a Brep (for Extrusions, etc.) try: geom = geom.ToBrep() except AttributeError as e: pass try: for srfc in geom.Faces: output.append(Geom(srfc, input_guid)) except AttributeError as e: output.append(Geom(geom, input_guid)) else: # Must be some Grasshopper Geometry being input try: for srfc in input_obj.Faces: output.append(Geom(srfc, None)) except AttributeError as e: output.append(Geom(input_obj, None)) return output
def retrieveGeometry(self, layers): geometry = [] sc.doc = Rhino.RhinoDoc.ActiveDoc for i, layer in enumerate(layers): objs = [rs.coercegeometry(obj) for obj in rs.ObjectsByLayer(layer)] if objs == None: objs = [] for i, obj in enumerate(objs): if type(obj) == Rhino.Geometry.Point: objs[i] = Rhino.Geometry.Point3d(obj.Location) geometry.append(objs) sc.doc = ghdoc return geometry
def getNormalLine(mayForm, cardinal, pos1, pos2, tier1, tier2): points = [] points.append(mayForm.latticeEndPoints[cardinal][tier2][pos1]) points.append(mayForm.latticeEndPoints[cardinal][tier1][pos1]) points.append(mayForm.latticeEndPoints[cardinal][tier1][pos2]) points.append(mayForm.latticeEndPoints[cardinal][tier2][pos2]) points.append(mayForm.latticeEndPoints[cardinal][tier2][pos1]) points = [rs.coercegeometry(point).Location for point in points] polyline = rs.AddPolyline(points) flatPolyline = flattenPolyline(polyline, points[0], points[1], points[2], points[3])[0] normal = rs.CurveNormal(flatPolyline) rs.DeleteObject(polyline) normal = rs.VectorScale(normal, 100) centerPoint = ( points[0] + points[1] + points[2] + points[3]) / 4 point1 = rs.PointAdd(centerPoint, normal) point2 = rs.PointAdd(centerPoint, -normal) line = rs.AddLine(point1, point2) return line
def AddToBlock(): objects = rs.GetObjects("Choose Objects to Add to Block", preselect=True) if not objects: return block = rs.GetObject("Choose Block to Add Object to", rs.filter.instance) if not block: return rs.EnableRedraw(False) blockName = rs.BlockInstanceName(block) objref = rs.coercerhinoobject(block) idef = objref.InstanceDefinition idefIndex = idef.Index if rs.IsBlockReference(blockName): print "Block is referenced from file; unable to add object(s)" return blnCopy = False XformBlock = rs.BlockInstanceXform(block) rs.TransformObjects(objects, rs.XformInverse(XformBlock), blnCopy) objects.extend(rs.BlockObjects(blockName)) newGeometry = [] newAttributes = [] for object in objects: newGeometry.append(rs.coercegeometry(object)) ref = Rhino.DocObjects.ObjRef(object) attr = ref.Object().Attributes newAttributes.append(attr) InstanceDefinitionTable = sc.doc.ActiveDoc.InstanceDefinitions InstanceDefinitionTable.ModifyGeometry(idefIndex, newGeometry, newAttributes) rs.DeleteObjects(objects) rs.EnableRedraw(True)
def find_all_tfa_surfaces( _tfa_surfaces, _ghenv, _ghdoc ): input_num = _TFA_surfaces_input_number(_ghenv) rhino_tfa_objects = [] for i, tfa_input in enumerate(_tfa_surfaces): rhino_guid = _ghenv.Component.Params.Input[input_num].VolatileData[0][i].ReferenceID rhino_obj = Rhino.RhinoDoc.ActiveDoc.Objects.Find( rhino_guid ) if rhino_obj: # Input is a Rhino surface with LBT2PH.helpers.context_rh_doc(_ghdoc): tfa_obj = get_tfa_surface_data_from_Rhino( rhino_guid ) rhino_tfa_objects.append( tfa_obj ) else: # Input is a Grasshoppper-generated surface geom = rs.coercegeometry( tfa_input ) params = {} tfa_obj = ( geom, params ) rhino_tfa_objects.append( tfa_obj ) return rhino_tfa_objects
def slabMulti(id, index, lasercutLayer): rs.EnableRedraw(False) extru = rs.coercegeometry(id) pathStart = extru.PathStart pathEnd = extru.PathEnd start_curve = extru.Profile3d(0,0) baseCrv = scriptcontext.doc.Objects.AddCurve(start_curve) rs.ObjectLayer(baseCrv, layer=lasercutLayer) dist = rs.Distance(pathStart, pathEnd) num = int(dist // 4000) box = rs.BoundingBox(id) vecCopyUni = rs.VectorSubtract(box[0], box[3]) groupName = "group" + str(index) # rs.AddGroup(groupName) item = [] text = rs.AddText(str(index), box[3], height=textHeight) # rs.AddObjectToGroup(text, groupName) item += [text] for i in range(num): vecCopy = rs.VectorScale(vecCopyUni, i) crvCopied = rs.CopyObject(baseCrv, vecCopy) # rs.AddObjectToGroup(crvCopied, groupName) item += [crvCopied] return item
def unionAllFans(solarFans): res = [] for fanCount in range(0, len(solarFans), 2): try: sc.doc = rc.RhinoDoc.ActiveDoc #change target document rs.EnableRedraw(False) guid1 = sc.doc.Objects.AddBrep(solarFans[fanCount]) guid2 = sc.doc.Objects.AddBrep(solarFans[fanCount + 1]) all = rs.BooleanUnion([guid1, guid2], True) if all: a = [rs.coercegeometry(a) for a in all] for g in a: g.EnsurePrivateCopy() #must ensure copy if we delete from doc rs.DeleteObjects(all) sc.doc = ghdoc #put back document rs.EnableRedraw() if a == None: a = [solarFans[fanCount], solarFans[fanCount + 1]] except: if guid1: rs.DeleteObjects(guid1) if guid2: rs.DeleteObjects(guid2) if all: rs.DeleteObjects(all) sc.doc = ghdoc #put back document rs.EnableRedraw() a = [solarFans[fanCount]] if a: res.extend(a) return res
def checkInputData(analysisGeometry, contextMeshes, north, scale, outputGeometryIndex, workingFolderPath, horizonFileType): pathsAnalysisGeometry = analysisGeometry.Paths analysisGeometryBranchesLists = analysisGeometry.Branches srfCornerPtsLL = [] srfCentroidL = [] selfShadingAnalysisGeometry = [] # self shading will not be applied, even though this list is created for branchIndex,branchList in enumerate(analysisGeometryBranchesLists): # all branches have a single item in its list if len(branchList) > 0: # branch list is not empty id = list(branchList)[0] obj = rs.coercegeometry(id) # input is a point if isinstance(obj, Rhino.Geometry.Point): srfCornerPts = [obj.Location] srfCentroid = obj.Location # input is brep elif isinstance(obj, Rhino.Geometry.Brep): selfShadingAnalysisGeometry.append(obj) facesCount = obj.Faces.Count if facesCount > 1: # inputted polysurface srfCornerPts = [] srfCentroid = None printMsg = "One or more of the breps you supplied to \"_analysisGeometry\" is a polysurface. Please supply a surface instead." level = gh.GH_RuntimeMessageLevel.Warning ghenv.Component.AddRuntimeMessage(level, printMsg) print printMsg else: # inputted brep with a single surface srfCornerPts = obj.DuplicateVertices() srfCentroid = Rhino.Geometry.AreaMassProperties.Compute(obj).Centroid else: # any other geometry than surface and point srfCornerPts = [] srfCentroid = None printMsg = "One or more of the geometry you supplied to \"_analysisGeometry\" is not a surface nor a point, which is what \"_analysisGeometry\" requires as an input." level = gh.GH_RuntimeMessageLevel.Warning ghenv.Component.AddRuntimeMessage(level, printMsg) print printMsg elif len(branchList) == 0: # empty branches srfCornerPts = [] srfCornerPtsLL.append(srfCornerPts) srfCentroidL.append(srfCentroid) # check if _analysisGeometry input contains only "None" values NoneItemsIn_srfCentroidL = 0 for item in srfCentroidL: if item == None: NoneItemsIn_srfCentroidL += 1 if len(srfCentroidL) == NoneItemsIn_srfCentroidL: srfCornerPtsLL = srfCentroidL = srfCentroid = contextMeshJoined = northRad = northVec = scale = outputGeometryIndex = workingSubFolderPath = horizonFileType = horizonFileTypeLabel = unitConversionFactor = None validInputData = False printMsg = "The value(s) you supplied to the \"_analysisGeometry\" input are neither points nor surfaces.\n" + \ "Please input one of these." return srfCornerPtsLL, srfCentroidL, srfCentroid, contextMeshJoined, northRad, northVec, scale, outputGeometryIndex, workingSubFolderPath, horizonFileType, horizonFileTypeLabel, unitConversionFactor, validInputData, printMsg # check if something inputted into "context_" input if len(contextMeshes) == 0: srfCornerPtsLL = srfCentroidL = srfCentroid = contextMeshJoined = northRad = northVec = scale = outputGeometryIndex = workingSubFolderPath = horizonFileType = horizonFileTypeLabel = unitConversionFactor = None validInputData = False printMsg = "Input the \"terrainShadingMask\" output from \"Terrain shading mask\" component.\n" + \ "You can additionally input other opaque obstacles surrounding your location: houses, buildings etc.\n" + \ "Do not input trees, as they are not opaque obstacles and should not be taken into account when analysing the horizon angles." return srfCornerPtsLL, srfCentroidL, srfCentroid, contextMeshJoined, northRad, northVec, scale, outputGeometryIndex, workingSubFolderPath, horizonFileType, horizonFileTypeLabel, unitConversionFactor, validInputData, printMsg else: # remove "None" from context_ contextMeshesFiltered = [] for mesh in contextMeshes: if mesh != None: contextMeshesFiltered.append(mesh) contextMeshJoined = Rhino.Geometry.Mesh() for filteredContextMesh in contextMeshesFiltered: contextMeshJoined.Append(filteredContextMesh) if (north == None): northRad = 0 # default, in radians northVec = Rhino.Geometry.Vector3d(0,1,0) else: try: # check if it's a number north = float(north) if north < 0 or north > 360: srfCornerPtsLL = srfCentroidL = srfCentroid = contextMeshJoined = northRad = northVec = scale = outputGeometryIndex = workingSubFolderPath = horizonFileType = horizonFileTypeLabel = unitConversionFactor = None validInputData = False printMsg = "Please input north angle value from 0 to 360." return srfCornerPtsLL, srfCentroidL, srfCentroid, contextMeshJoined, northRad, northVec, scale, outputGeometryIndex, workingSubFolderPath, horizonFileType, horizonFileTypeLabel, unitConversionFactor, validInputData, printMsg except Exception, e: # check if it's a vector north.Unitize() northRad, northVec = lb_photovoltaics.angle2northClockwise(north)
def checkTheInputs(): #Call the necessary HB functions from the hive. hb_hive = sc.sticky["honeybee_Hive"]() hb_EPObjectsAux = sc.sticky["honeybee_EPObjectsAUX"]() #Have a function to duplicate data. def duplicateData(data, calcLength): dupData = [] for count in range(calcLength): dupData.append(data[0]) return dupData #Create lists to be filled. srfAreas = [] #Check to see if the input in the _srfsOrSrfArea is a number of geometry. checkData1 = False try: #Object is a surface area number. srfArea = float(_srfsOrSrfArea[0]) srfMethod = 1 #Number is a single value to applied to all connected zones. if len(_srfsOrSrfArea) == 1: srfAreas = duplicateData([float(_srfsOrSrfArea[0])], len(_HBZones)) checkData1 = True #Number is list of numbers that match the connected zones. elif len(_srfsOrSrfArea) == len(_HBZones): srfMethod = 0 for item in _srfsOrSrfArea: srfAreas.append(float(item)) checkData1 = True else: warning = "Numerical inputs for _srfsOrSrfArea must be either a list that matches the number of HBZones or a single value to be applied to all HBZones." print warning ghenv.Component.AddRuntimeMessage(w, warning) except: try: #Object is a set of surfaces. srfBreps = [] srfVerts = [] for item in _srfsOrSrfArea: srfBrep = [rs.coercegeometry(srfBrep) for srfBrep in [item]][0] srfVert = srfBrep.DuplicateVertices() srfBreps.append(srfBrep) srfVerts.append(srfVert) checkData1 = True #Create a list to hold the total surface areas inside each zone. brepZoneCount = [] for zone in _HBZones: brepZoneCount.append(0) srfAreas.append(0) #Test to see if any of the breps lie completely inside a zone. for count, brep in enumerate(srfBreps): brepZoneCounter = brepZoneCount[:] for zoneCount, zone in enumerate(_HBZones): for vertex in srfVerts[count]: if zone.IsPointInside(rc.Geometry.Point3d(vertex), tol, False): brepZoneCounter[zoneCount] += 1 if brepZoneCounter[zoneCount] == len(srfVerts[count]): #The surface is completely inside the zone. area = rc.Geometry.AreaMassProperties.Compute(brep).Area*sc.sticky["honeybee_ConversionFactor"]*sc.sticky["honeybee_ConversionFactor"] srfAreas[zoneCount] += area #Give a warning if a surface was not found to lie completely inside any zone. if len(srfVerts[count]) not in brepZoneCounter: checkData1 = False warning = "One of the surfaces input to _srfsOrSrfArea does not lie completely in a single HBZone. \n All surfaces must lie COMPLETELY inside a single zone and cannot span between zones or span outside the building. \n If you have an object that lies between two zones, please split it in two along the boundary between the zones." print warning ghenv.Component.AddRuntimeMessage(w, warning) except: warning = "Input for _srfsOrSrfArea is invalid." print warning ghenv.Component.AddRuntimeMessage(w, warning) #Check to be sure that the EPConstruction is in the library or can be added to the library. checkData2 = True # if it is just the name of the material make sure it is already defined if len(_EPConstruction.split("\n")) == 1: # if the material is not in the library add it to the library if not hb_EPObjectsAux.isEPConstruction(_EPConstruction): warningMsg = "Can't find " + _EPConstruction + " in EP Construction Library.\n" + \ "Add the construction to the library and try again." print warningMsg ghenv.Component.AddRuntimeMessage(gh.GH_RuntimeMessageLevel.Warning, warningMsg) checkData2 = False else: EPConstruction = _EPConstruction else: # It is a full string added, EPConstruction = hb_EPObjectsAux.addEPObjectToLib(_EPConstruction, overwrite = True) if not added: msg = _EPConstruction + " is not added to the project library!" ghenv.Component.AddRuntimeMessage(gh.GH_RuntimeMessageLevel.Warning, msg) print msg checkData2 = False #Check to be sure that the HBZones are valid HBZones. checkData3 = True try: HBZones = hb_hive.callFromHoneybeeHive(_HBZones) except: HBZones = [] checkData3 = False warning = "Connected _HBZones are not valid." print warning ghenv.Component.AddRuntimeMessage(w, warning) #Check to see if there is an internalMassName_ attached. massNames = [] if internalMassName_ != None: for zone in HBZones: massName = zone.name + "-" + internalMassName_ massNames.append(massName) else: for zone in HBZones: massName = zone.name + "-" + "Mass" + str(len(zone.internalMassNames)) massNames.append(massName) #Check to be sure that everything is ok. if checkData1 == True and checkData2 == True and checkData3 == True: checkData = True else: checkData = False return checkData, HBZones, srfAreas, EPConstruction, massNames
def PVsurfaceInputData(PVsurface, PVsurfacePercent, unitAreaConversionFactor, DCtoACderateFactor, moduleActiveAreaPercent, moduleType, moduleEfficiency): if (PVsurface == None): PVsurfaceInputType = nameplateDCpowerRating = srfArea = activeArea = PVsurfacePercent = DCtoACderateFactor = moduleActiveAreaPercent = moduleType = moduleEfficiency = None validPVsurfaceData = False printMsg = "Please input Surface (not polysurface) to \"_PVsurface\".\nOr input surface Area in square meters (example: \"100\").\nOr input Nameplate DC power rating in kiloWatts (example: \"4 kw\")." return PVsurfaceInputType, nameplateDCpowerRating, srfArea, activeArea, PVsurfacePercent, DCtoACderateFactor, moduleActiveAreaPercent, moduleType, moduleEfficiency, validPVsurfaceData, printMsg if (PVsurfacePercent == None) or (PVsurfacePercent < 0) or (PVsurfacePercent > 100): PVsurfacePercent = 100 # default value 100% if (DCtoACderateFactor == None) or (DCtoACderateFactor < 0) or (DCtoACderateFactor > 1): DCtoACderateFactor = 0.85 # default value (corresponds to 11.42% of PVWatts v5 Total Losses) if (moduleActiveAreaPercent == None) or (moduleActiveAreaPercent < 0) or (moduleActiveAreaPercent > 100): moduleActiveAreaPercent = 90 # default value in % if (moduleType == None) or (moduleType < 0) or (moduleType > 3): moduleType = 0 # Glass/cell/glass, Close (flush) roof mount if (moduleEfficiency == None) or (moduleEfficiency < 0) or (moduleEfficiency > 100): moduleEfficiency = 15 # for crystalline silicon # check PVsurface input obj = rs.coercegeometry(PVsurface) # input is surface if isinstance(obj,Rhino.Geometry.Brep): PVsurfaceInputType = "brep" facesCount = obj.Faces.Count if facesCount > 1: # inputted polysurface PVsurfaceInputType = nameplateDCpowerRating = srfArea = activeArea = PVsurfacePercent = DCtoACderateFactor = moduleActiveAreaPercent = moduleType = moduleEfficiency = None validPVsurfaceData = False printMsg = "The brep you supplied to \"_PVsurface\" is a polysurface. Please supply a surface" return PVsurfaceInputType, nameplateDCpowerRating, srfArea, activeArea, PVsurfacePercent, DCtoACderateFactor, moduleActiveAreaPercent, moduleType, moduleEfficiency, validPVsurfaceData, printMsg else: # inputted brep with a single surface srfArea = Rhino.Geometry.AreaMassProperties.Compute(obj).Area * (PVsurfacePercent/100) # in m2 srfArea = srfArea * unitAreaConversionFactor # in m2 activeArea = srfArea * (moduleActiveAreaPercent/100) # in m2 nameplateDCpowerRating = activeArea * (1 * (moduleEfficiency/100)) # in kW validPVsurfaceData = True printMsg = "ok" return PVsurfaceInputType, nameplateDCpowerRating, srfArea, activeArea, PVsurfacePercent, DCtoACderateFactor, moduleActiveAreaPercent, moduleType, moduleEfficiency, validPVsurfaceData, printMsg else: PVsurfaceInputType = "number" try: # input is number (pv surface area in m2) srfArea = float(PVsurface) * (PVsurfacePercent/100) # in m2 srfArea = srfArea * unitAreaConversionFactor # in m2 activeArea = srfArea * (moduleActiveAreaPercent/100) # in m2 nameplateDCpowerRating = activeArea * (1 * (moduleEfficiency/100)) # in kW validPVsurfaceData = True printMsg = "ok" return PVsurfaceInputType, nameplateDCpowerRating, srfArea, activeArea, PVsurfacePercent, DCtoACderateFactor, moduleActiveAreaPercent, moduleType, moduleEfficiency, validPVsurfaceData, printMsg except Exception, e: pass # input is string (nameplateDCpowerRating in kW) lowerString = PVsurface.lower() if "kw" in lowerString: nameplateDCpowerRating = float(lowerString.replace("kw","")) * (PVsurfacePercent/100) # in kW activeArea = nameplateDCpowerRating / (1 * (moduleEfficiency/100)) # in m2 srfArea = activeArea * (100/moduleActiveAreaPercent) # in m2 validPVsurfaceData = True printMsg = "ok" return PVsurfaceInputType, nameplateDCpowerRating, srfArea, activeArea, PVsurfacePercent, DCtoACderateFactor, moduleActiveAreaPercent, moduleType, moduleEfficiency, validPVsurfaceData, printMsg else: PVsurfaceInputType = nameplateDCpowerRating = srfArea = activeArea = PVsurfacePercent = DCtoACderateFactor = moduleActiveAreaPercent = moduleType = moduleEfficiency = None validPVsurfaceData = False printMsg = "Something is wrong with your \"PVsurface\" input data" return PVsurfaceInputType, nameplateDCpowerRating, srfArea, activeArea, PVsurfacePercent, DCtoACderateFactor, moduleActiveAreaPercent, moduleType, moduleEfficiency, validPVsurfaceData, printMsg
def checkTheInputs(): #Call the necessary HB functions from the hive. hb_hive = sc.sticky["honeybee_Hive"]() hb_EPObjectsAux = sc.sticky["honeybee_EPObjectsAUX"]() #Have a function to duplicate data. def duplicateData(data, calcLength): dupData = [] for count in range(calcLength): dupData.append(data[0]) return dupData #Create lists to be filled. srfAreas = [] #Check to see if the input in the _srfsOrSrfArea is a number of geometry. checkData1 = False try: #Object is a surface area number. srfArea = float(_srfsOrSrfArea[0]) srfMethod = 1 #Number is a single value to applied to all connected zones. if len(_srfsOrSrfArea) == 1: srfAreas = duplicateData(float(_srfsOrSrfArea[0]), len(_HBZones)) checkData1 = True #Number is list of numbers that match the connected zones. elif len(_srfsOrSrfArea) == len(_HBZones): srfMethod = 0 for item in _srfsOrSrfArea: srfAreas.append(float(item)) checkData1 = True else: warning = "Numerical inputs for _srfsOrSrfArea must be either a list that matches the number of HBZones or a single value to be applied to all HBZones." print warning ghenv.Component.AddRuntimeMessage(w, warning) except: try: #Object is a set of surfaces. srfBreps = [] srfVerts = [] for item in _srfsOrSrfArea: srfBrep = [rs.coercegeometry(srfBrep) for srfBrep in [item]][0] srfVert = srfBrep.DuplicateVertices() srfBreps.append(srfBrep) srfVerts.append(srfVert) checkData1 = True #Create a list to hold the total surface areas inside each zone. brepZoneCount = [] for zone in _HBZones: brepZoneCount.append(0) srfAreas.append(0) #Test to see if any of the breps lie completely inside a zone. for count, brep in enumerate(srfBreps): brepZoneCounter = brepZoneCount[:] for zoneCount, zone in enumerate(_HBZones): for vertex in srfVerts[count]: if zone.IsPointInside(rc.Geometry.Point3d(vertex), tol, False): brepZoneCounter[zoneCount] += 1 if brepZoneCounter[zoneCount] == len(srfVerts[count]): #The surface is completely inside the zone. area = rc.Geometry.AreaMassProperties.Compute( brep).Area srfAreas[zoneCount] += area #Give a warning if a surface was not found to lie completely inside any zone. if len(srfVerts[count]) not in brepZoneCounter: checkData1 = False warning = "One of the surfaces input to _srfsOrSrfArea does not lie completely in a single HBZone. \n All surfaces must lie COMPLETELY inside a single zone and cannot span between zones or span outside the building. \n If you have an object that lies between two zones, please split it in two along the boundary between the zones." print warning ghenv.Component.AddRuntimeMessage(w, warning) except: warning = "Input for _srfsOrSrfArea is invalid." print warning ghenv.Component.AddRuntimeMessage(w, warning) #Check to be sure that the EPConstruction is in the library or can be added to the library. checkData2 = True # if it is just the name of the material make sure it is already defined if len(_EPConstruction.split("\n")) == 1: # if the material is not in the library add it to the library if not hb_EPObjectsAux.isEPConstruction(_EPConstruction): warningMsg = "Can't find " + _EPConstruction + " in EP Construction Library.\n" + \ "Add the construction to the library and try again." print warningMsg ghenv.Component.AddRuntimeMessage( gh.GH_RuntimeMessageLevel.Warning, warningMsg) checkData2 = False else: EPConstruction = _EPConstruction else: # It is a full string added, EPConstruction = hb_EPObjectsAux.addEPObjectToLib( _EPConstruction, overwrite=True) if not added: msg = _EPConstruction + " is not added to the project library!" ghenv.Component.AddRuntimeMessage( gh.GH_RuntimeMessageLevel.Warning, msg) print msg checkData2 = False #Check to be sure that the HBZones are valid HBZones. checkData3 = True try: HBZones = hb_hive.callFromHoneybeeHive(_HBZones) except: HBZones = [] checkData3 = False warning = "Connected _HBZones are not valid." print warning ghenv.Component.AddRuntimeMessage(w, warning) #Check to see if there is an internalMassName_ attached. massNames = [] if internalMassName_ != None: for zone in HBZones: massName = zone.name + "-" + internalMassName_ massNames.append(massName) else: for zone in HBZones: massName = zone.name + "-" + "Mass" + str( len(zone.internalMassNames)) massNames.append(massName) #Check to be sure that everything is ok. if checkData1 == True and checkData2 == True and checkData3 == True: checkData = True else: checkData = False return checkData, HBZones, srfAreas, EPConstruction, massNames
# in case mass is not a list change it to list try: mass[0] except: mass = [mass] newMass = [] for brep in mass: if brep != None: #Bake the objects into the Rhino scene to ensure that surface normals are facing the correct direction sc.doc = rc.RhinoDoc.ActiveDoc #change target document rs.EnableRedraw(False) guid1 = [sc.doc.Objects.AddBrep(brep)] if guid1: a = [rs.coercegeometry(a) for a in guid1] for g in a: g.EnsurePrivateCopy( ) #must ensure copy if we delete from doc rs.DeleteObjects(guid1) sc.doc = ghdoc #put back document rs.EnableRedraw() newMass.append(g) mass = newMass try: splitBldgFloors.AddRange(mass, p) #zoneNames = [str(i) + "_" + str(m) for m in range(len(mass))] #names.AddRange(zoneNames, p)
def ColorMesh(MeshID, BlockID): MeshObj = rs.coercemesh(MeshID) MeshObj.EnsurePrivateCopy() Brep = rs.coercegeometry(BlockID) Brep.EnsurePrivateCopy() BB = rs.BoundingBox(BlockID) bb = rs.coerceboundingbox(BB).ToBrep() bb.EnsurePrivateCopy() time1a = time.time() #Start Timer tol = scriptcontext.doc.ModelAbsoluteTolerance Red = rs.coercecolor(System.Drawing.Color.Red) ## Too Low ## Orange = rs.coercecolor(System.Drawing.Color.Orange) Yellow = rs.coercecolor(System.Drawing.Color.Yellow) Green = rs.coercecolor(System.Drawing.Color.Green) ## Within Tol ## LtBlue = rs.coercecolor(System.Drawing.Color.LightBlue) Blue = rs.coercecolor(System.Drawing.Color.Blue) Purple = rs.coercecolor(System.Drawing.Color.Purple) ## Too High ## White = rs.coercecolor(System.Drawing.Color.White) Colors = [Purple, Blue, LtBlue, Green, Yellow, Orange, Red] ## \/ Set Tolerances Here \/ ## Range = [1 / 32, 1 / 16, 1 / 8] Build_Key(BB[5], Colors, Range) Rhino.RhinoApp.Wait() ColorList = range(MeshObj.Vertices.Count) def CalculateColor(i): Vertex = MeshObj.Vertices[i] Point = rs.coerce3dpoint(Vertex) if bb.IsPointInside(Point, tol, True) == False: Color = White else: CP = Brep.ClosestPoint(Point) Distance = Point.DistanceTo(CP) Color = None if Distance < Range[0]: Color = Colors[3] # Green # elif Distance < Range[1]: if Brep.IsPointInside(Point, tol, True) == True: Color = Colors[4] #Too Low else: Color = Colors[2] #Too High elif Distance < Range[2]: if Brep.IsPointInside(Point, tol, True) == True: Color = Colors[5] #Too Low else: Color = Colors[1] #Too High # Outside Range # else: if Brep.IsPointInside(Point, tol, True) == True: Color = Colors[6] #Too Low else: Color = Colors[0] #Too High ColorList[i] = Color print MeshObj.Vertices.Count ghpythonlib.parallel.run(CalculateColor, range(MeshObj.Vertices.Count)) for Color in ColorList: MeshObj.VertexColors.Add(Color) scriptcontext.doc.Objects.Replace(MeshID, MeshObj) scriptcontext.doc.Views.Redraw() ## Add Scale ## time1b = time.time() #End Timer print round(time1b - time1a, 3)
""" import copy import scriptcontext as sc import clr import random import rhinoscriptsyntax as rs clr.AddReference("Grasshopper") from Grasshopper.Kernel.Data import GH_Path from Grasshopper import DataTree if run: if add_collision!=[]: add_collision = filter(lambda n: n!=None,add_collision) add_collision = map(lambda c: rs.coercegeometry(c), add_collision) rule = DataTree[object]() rule_ = [\ ['separate', True],\ ['grammar_key','separate'],\ ['x_keep_omit',short_keep_omit],\ ['y_keep_omit',long_keep_omit],\ ['add_collision',add_collision],\ ['end_rule']] for i, r in enumerate(rule_): rule.Add(r) else: rule = []
conditionalStatement_, annualHourlyDataLists, annualHourlyDataListsEpwNames, [ directNormalRadiation, diffuseHorizontalRadiation ], True) if validConditionalStatement: directNormalRadiationCondStat, diffuseHorizontalRadiationCondStat = weatherPerHourDataConditionalStatementSubLists # all inputs ok if _runIt: SWHsurfaceTiltAngle_ = None SWHsurfaceAzimuthAngle_ = None SWHsurfaceInputType = "brep" srfAzimuthD, surfaceTiltDCalculated = lb_photovoltaics.srfAzimuthAngle( SWHsurfaceAzimuthAngle_, SWHsurfaceInputType, rs.coercegeometry(_SWHsurface), latitude) correctedSrfAzimuthD, northDeg, validNorth, printMsg = lb_photovoltaics.correctSrfAzimuthDforNorth( north_, srfAzimuthD) srfTiltD = lb_photovoltaics.srfTiltAngle( SWHsurfaceTiltAngle_, surfaceTiltDCalculated, SWHsurfaceInputType, rs.coercegeometry(_SWHsurface), latitude) heatFromTankPerHour, heatFromTankPerYear, avrDailyheatFromTankPerYear, heatFromAuxiliaryHeaterPerHour, dischargedHeatPerHour, pumpEnergyPerHour, tankWaterTemperaturePerHour = main( latitude, longitude, timeZone, locationName, years, months, days, hours, heatingLoadPerHourData, coldWaterTemperaturePerHour, activeArea, srfTiltD,
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
if validEpwData: unitConversionFactor = lb_preparation.checkUnits() unitAreaConversionFactor = unitConversionFactor**2 heatingLoadPerHourData, srfArea, SWHsurfacePercent, validHeatingLoadSWHsurface, printMsg = heatingLoadSWHsurfaceInputData(_heatingLoadPerHour, _SWHsurface, SWHsurfacePercent_, unitAreaConversionFactor) if validHeatingLoadSWHsurface: coldWaterTemperaturePerHour, activeArea, nameplateThermalCapacity, SWHsystemSettings, validSWHsystemSettings, printMsg = SWHsystemSettingsInput(heatingLoadPerHourData, SWHsystemSettings_, srfArea, dryBulbTemperature) if validSWHsystemSettings: validAnnualHourlyData, annualHourlyDataLists, annualHourlyDataListsEpwNames, printMsg = checkAnnualHourlyInputData(annualHourlyData_) if validAnnualHourlyData: validConditionalStatement, weatherPerHourDataConditionalStatementSubLists, conditionalStatementForFinalPrint, printMsg = checkConditionalStatement(conditionalStatement_, annualHourlyDataLists, annualHourlyDataListsEpwNames, [directNormalRadiation, diffuseHorizontalRadiation], True) if validConditionalStatement: directNormalRadiationCondStat, diffuseHorizontalRadiationCondStat = weatherPerHourDataConditionalStatementSubLists # all inputs ok if _runIt: SWHsurfaceTiltAngle_ = None; SWHsurfaceAzimuthAngle_ = None; SWHsurfaceInputType = "brep" srfAzimuthD, surfaceTiltDCalculated = lb_photovoltaics.srfAzimuthAngle(SWHsurfaceAzimuthAngle_, SWHsurfaceInputType, rs.coercegeometry(_SWHsurface), latitude) correctedSrfAzimuthD, northDeg, validNorth, printMsg = lb_photovoltaics.correctSrfAzimuthDforNorth(north_, srfAzimuthD) srfTiltD = lb_photovoltaics.srfTiltAngle(SWHsurfaceTiltAngle_, surfaceTiltDCalculated, SWHsurfaceInputType, rs.coercegeometry(_SWHsurface), latitude) heatFromTankPerHour, heatFromTankPerYear, avrDailyheatFromTankPerYear, heatFromAuxiliaryHeaterPerHour, dischargedHeatPerHour, pumpEnergyPerHour, tankWaterTemperaturePerHour = main(latitude, longitude, timeZone, locationName, years, months, days, hours, heatingLoadPerHourData, coldWaterTemperaturePerHour, activeArea, srfTiltD, correctedSrfAzimuthD, dryBulbTemperature, directNormalRadiationCondStat, diffuseHorizontalRadiationCondStat, albedoL, SWHsystemSettings, conditionalStatementForFinalPrint) printOutput(locationName, latitude, longitude, northDeg, albedoL, heatingLoadPerHourData, SWHsurfacePercent, srfArea, activeArea, nameplateThermalCapacity, srfAzimuthD, srfTiltD, SWHsystemSettings, conditionalStatementForFinalPrint) SWHsurfaceTiltAngle = srfTiltD; SWHsurfaceAzimuthAngle = correctedSrfAzimuthD; systemSize = nameplateThermalCapacity else: print "All inputs are ok. Please set the \"_runIt\" to True, in order to run the Solar water heating surface component" else: print printMsg ghenv.Component.AddRuntimeMessage(level, printMsg) else: print printMsg ghenv.Component.AddRuntimeMessage(level, printMsg) else: print printMsg
def checkInputData(geometryIds, numOfInitialPts, initialPtsSpread, stepSize, flowPathsType): # check inputs if len(geometryIds) == 0: geometryMesh = numOfInitialPts = initialPtsSpread = initialPtsSpreadLabel = stepSize = flowPathsType = flowPathsTypeLabel = None validInputData = False printMsg = "\"_geometry\" input is empty.\n" + \ "Please supply a surface and/or polysurface and/or mesh for which you would like to conduct the flow path analysis (that can be a building, terrain, landscape or any other sort of geometry)." return geometryMesh, numOfInitialPts, initialPtsSpread, initialPtsSpreadLabel, stepSize, flowPathsType, flowPathsTypeLabel, validInputData, printMsg if (numOfInitialPts == None): numOfInitialPts = 100 # default elif (numOfInitialPts < 2): print "\"numOfInitialPts_\" input can not be less than 2.\n" + \ "\"numOfInitialPts_\" input set to 2." numOfInitialPts = 2 if (initialPtsSpread == None): initialPtsSpread = 1 # default (Random) initialPtsSpreadLabel = "Random" if (initialPtsSpread == 0): initialPtsSpreadLabel = "Rectangular grid" elif (initialPtsSpread == 1): initialPtsSpreadLabel = "Random" else: print "\"initialPtsSpread_\" input only accepts values: 0 (Rectangular grid) and 1 (Random).\n" + \ "\"initialPtsSpread_\" input set to 1 (Random)." initialPtsSpread = 1 initialPtsSpreadLabel = "Random" if (stepSize == None): stepSize = 1 # default (in rhino document units) elif (stepSize < 0.01): print "\"stepSize_\" input only accepts values larger 0.01 rhino document units (meters, feet, inches...).\n" + \ "\"stepSize_\" input set to 1 rhino document unit." stepSize = 1 if (flowPathsType == None): flowPathsType = 0 # default (polylines) flowPathsTypeLabel = "Polylines" if (flowPathsType == 0): flowPathsTypeLabel = "Polylines" elif (flowPathsType == 1): flowPathsTypeLabel = "Curves" else: print "\"flowPathsType_\" input only accepts values: 0 (Polylines) and 1 (Curves).\n" + \ "\"flowPathsType_\" input set to 0 (Polylines)." flowPathsType = 0 flowPathsTypeLabel = "Polylines" # create a geometryMesh from _geometry inputs geometryMesh = Rhino.Geometry.Mesh() # joined mesh of all geometry supplied into the "_geometry" input geometryObjs = [rs.coercegeometry(geometryId) for geometryId in geometryIds] for geometryObj in geometryObjs: if isinstance(geometryObj, Rhino.Geometry.Mesh): geometryMesh.Append(geometryObj) elif isinstance(geometryObj, Rhino.Geometry.Brep): meshParam = Rhino.Geometry.MeshingParameters() #meshParam.MaximumEdgeLength = maxEdgeLength_ # more beneficial for drainage area per flow direction meshParam.SimplePlanes = True meshesFromBrep = Rhino.Geometry.Mesh.CreateFromBrep(geometryObj, meshParam) for mesh in meshesFromBrep: geometryMesh.Append(mesh) if geometryMesh.IsValid == True: # a brep and/or a mesh supplied to "_geometry" input pass else: # neither mesh nor brep object(s) have been supplied into the "_geometry" input geometryMesh = numOfInitialPts = initialPtsSpread = initialPtsSpreadLabel = stepSize = flowPathsType = flowPathsTypeLabel = None validInputData = False printMsg = "The data you supplied to the \"_geometry\" input is neither a surface and/or polysurface and/or mesh.\n" + \ "Please input some (or all) of these types of data to the \"_geometry\" input." return geometryMesh, numOfInitialPts, initialPtsSpread, initialPtsSpreadLabel, stepSize, flowPathsType, flowPathsTypeLabel, validInputData, printMsg validInputData = True printMsg = "ok" return geometryMesh, numOfInitialPts, initialPtsSpread, initialPtsSpreadLabel, stepSize, flowPathsType, flowPathsTypeLabel, validInputData, printMsg
def trimCurveGuids(curve, p1Guid, p2Guid): p1Coords = rs.coercegeometry(p1Guid).Location p2Coords = rs.coercegeometry(p2Guid).Location return trimCurve(curve, p1Coords, p2Coords)
p = GH_Path(i,j) # in case mass is not a list change it to list try: mass[0] except: mass = [mass] newMass = [] for brep in mass: if brep != None: #Bake the objects into the Rhino scene to ensure that surface normals are facing the correct direction sc.doc = rc.RhinoDoc.ActiveDoc #change target document rs.EnableRedraw(False) guid1 = [sc.doc.Objects.AddBrep(brep)] if guid1: a = [rs.coercegeometry(a) for a in guid1] for g in a: g.EnsurePrivateCopy() #must ensure copy if we delete from doc rs.DeleteObjects(guid1) sc.doc = ghdoc #put back document rs.EnableRedraw() newMass.append(g) mass = newMass try: splitBldgFloors.AddRange(mass, p) #zoneNames = [str(i) + "_" + str(m) for m in range(len(mass))] #names.AddRange(zoneNames, p) except: splitBldgFloors.Add(mass, p)
def PVinputData(PVsurface, PVsurfacePercent, unitConversionFactor, moduleActiveAreaPercent, moduleEfficiency, lifetime, ACenergyPerHour, totalRadiationPerHour, cellTemperaturePerHour, ACenergyDemandPerHour, energyCostPerKWh, embodiedEnergyPerM2, embodiedCO2PerM2, gridEfficiency): if (PVsurface == None): nameplateDCpowerRating = srfArea = activeArea = PVsurfacePercent = moduleActiveAreaPercent = moduleEfficiency = lifetime = ACenergyPerHourData = totalRadiationPerHourData = cellTemperaturePerHourData = ACenergyDemandPerHourData = energyCostPerKWh = embodiedEnergyPerM2 = embodiedCO2PerM2 = gridEfficiency = locationName = None validInputData = False printMsg = "Please input Surface (not polysurface) to \"_PVsurface\".\nOr input surface Area in square meters (example: \"100\").\nOr input Nameplate DC power rating in kiloWatts (example: \"4 kw\")." return nameplateDCpowerRating, srfArea, activeArea, PVsurfacePercent, moduleActiveAreaPercent, moduleEfficiency, lifetime, ACenergyPerHourData, totalRadiationPerHourData, cellTemperaturePerHourData, ACenergyDemandPerHourData, energyCostPerKWh, embodiedEnergyPerM2, embodiedCO2PerM2, gridEfficiency, locationName, validInputData, printMsg if (len(ACenergyPerHour) == 8767): ACenergyPerHourData = ACenergyPerHour[7:] locationName = ACenergyPerHour[1] elif (len(ACenergyPerHour) == 8760): ACenergyPerHourData = ACenergyPerHour locationName = "unknown location" elif (len(ACenergyPerHour) == 0) or (ACenergyPerHour[0] is "") or (ACenergyPerHour[0] is None) or ((len(ACenergyPerHour) != 8767) and (len(ACenergyPerHour) != 8760)): nameplateDCpowerRating = srfArea = activeArea = PVsurfacePercent = moduleActiveAreaPercent = moduleEfficiency = lifetime = ACenergyPerHourData = totalRadiationPerHourData = cellTemperaturePerHourData = ACenergyDemandPerHourData = energyCostPerKWh = embodiedEnergyPerM2 = embodiedCO2PerM2 = gridEfficiency = locationName = None validInputData = False printMsg = "Please input \"_ACenergyPerHour\" from Ladybug \"Photovoltaics surface\" component." return nameplateDCpowerRating, srfArea, activeArea, PVsurfacePercent, moduleActiveAreaPercent, moduleEfficiency, lifetime, ACenergyPerHourData, totalRadiationPerHourData, cellTemperaturePerHourData, ACenergyDemandPerHourData, energyCostPerKWh, embodiedEnergyPerM2, embodiedCO2PerM2, gridEfficiency, locationName, validInputData, printMsg if (len(totalRadiationPerHour) == 8767): totalRadiationPerHourData = totalRadiationPerHour[7:] elif (len(totalRadiationPerHour) == 8760): totalRadiationPerHourData = totalRadiationPerHour elif (len(totalRadiationPerHour) == 0) or (totalRadiationPerHour[0] is "") or (totalRadiationPerHour[0] is None) or ((len(totalRadiationPerHour) != 8767) and (len(totalRadiationPerHour) != 8760)): nameplateDCpowerRating = srfArea = activeArea = PVsurfacePercent = moduleActiveAreaPercent = moduleEfficiency = lifetime = ACenergyPerHourData = totalRadiationPerHourData = cellTemperaturePerHourData = ACenergyDemandPerHourData = energyCostPerKWh = embodiedEnergyPerM2 = embodiedCO2PerM2 = gridEfficiency = locationName = None validInputData = False printMsg = "Please input \"_totalRadiationPerHour\" from Ladybug \"Photovoltaics surface\" component." return nameplateDCpowerRating, srfArea, activeArea, PVsurfacePercent, moduleActiveAreaPercent, moduleEfficiency, lifetime, ACenergyPerHourData, totalRadiationPerHourData, cellTemperaturePerHourData, ACenergyDemandPerHourData, energyCostPerKWh, embodiedEnergyPerM2, embodiedCO2PerM2, gridEfficiency, locationName, validInputData, printMsg if (len(cellTemperaturePerHour) == 8767): cellTemperaturePerHourData = cellTemperaturePerHour[7:] elif (len(cellTemperaturePerHour) == 8760): cellTemperaturePerHourData = cellTemperaturePerHour elif (len(cellTemperaturePerHour) == 0) or (cellTemperaturePerHour[0] is "") or (cellTemperaturePerHour[0] is None) or ((len(cellTemperaturePerHour) != 8767) and (len(cellTemperaturePerHour) != 8760)): nameplateDCpowerRating = srfArea = activeArea = PVsurfacePercent = moduleActiveAreaPercent = moduleEfficiency = lifetime = ACenergyPerHourData = totalRadiationPerHourData = cellTemperaturePerHourData = ACenergyDemandPerHourData = energyCostPerKWh = embodiedEnergyPerM2 = embodiedCO2PerM2 = gridEfficiency = locationName = None validInputData = False printMsg = "Please input \"_cellTemperaturePerHour\" from Ladybug \"Photovoltaics surface\" component." return nameplateDCpowerRating, srfArea, activeArea, PVsurfacePercent, moduleActiveAreaPercent, moduleEfficiency, lifetime, ACenergyPerHourData, totalRadiationPerHourData, cellTemperaturePerHourData, ACenergyDemandPerHourData, energyCostPerKWh, embodiedEnergyPerM2, embodiedCO2PerM2, gridEfficiency, locationName, validInputData, printMsg if (len(ACenergyDemandPerHour) == 0) or (ACenergyDemandPerHour[0] is "") or (ACenergyDemandPerHour[0] is None): ACenergyDemandPerHourData = [0 for i in range(8760)] elif (len(ACenergyDemandPerHour) == 8767): ACenergyDemandPerHourData = ACenergyDemandPerHour[7:] elif (len(ACenergyDemandPerHour) == 8760): ACenergyDemandPerHourData = ACenergyDemandPerHour elif ((len(ACenergyDemandPerHour) != 8767) and (len(ACenergyDemandPerHour) != 8760)): nameplateDCpowerRating = srfArea = activeArea = PVsurfacePercent = moduleActiveAreaPercent = moduleEfficiency = lifetime = ACenergyPerHourData = totalRadiationPerHourData = cellTemperaturePerHourData = ACenergyDemandPerHourData = energyCostPerKWh = embodiedEnergyPerM2 = embodiedCO2PerM2 = gridEfficiency = locationName = None validInputData = False printMsg = "Your \"ACenergyDemandPerHour_\" input needs to contain 8760 values or 8767 items (8760 values + 7 heading strings)." return nameplateDCpowerRating, srfArea, activeArea, PVsurfacePercent, moduleActiveAreaPercent, moduleEfficiency, lifetime, ACenergyPerHourData, totalRadiationPerHourData, cellTemperaturePerHourData, ACenergyDemandPerHourData, energyCostPerKWh, embodiedEnergyPerM2, embodiedCO2PerM2, gridEfficiency, locationName, validInputData, printMsg if (PVsurfacePercent == None) or (PVsurfacePercent < 0) or (PVsurfacePercent > 100): PVsurfacePercent = 100 # default value 100% if (moduleActiveAreaPercent == None) or (moduleActiveAreaPercent < 0) or (moduleActiveAreaPercent > 100): moduleActiveAreaPercent = 90 # default value in % if (moduleEfficiency == None) or (moduleEfficiency < 0) or (moduleEfficiency > 100): moduleEfficiency = 15 # default for crystalline silicon, in % if (lifetime == None) or (lifetime < 0): lifetime = 30 # default, in years if (energyCostPerKWh == None) or (energyCostPerKWh < 0): energyCostPerKWh = 0.15 # dollars per kWh if (embodiedEnergyPerM2 == None) or (embodiedEnergyPerM2 < 0): embodiedEnergyPerM2 = 4410/1000 # default, in GJ/m2 else: embodiedEnergyPerM2 = embodiedEnergyPerM2/1000 # in in GJ/m2 if (embodiedCO2PerM2 == None) or (embodiedCO2PerM2 < 0): embodiedCO2PerM2 = 225/1000 # default, in t CO2/m2 else: embodiedCO2PerM2 = embodiedCO2PerM2/1000 # in t CO2/m2 if (gridEfficiency == None) or (gridEfficiency < 0) or (gridEfficiency > 100): gridEfficiency = 29 # default, in % # check PVsurface input obj = rs.coercegeometry(PVsurface) # input is surface if isinstance(obj,Rhino.Geometry.Brep): PVsurfaceInputType = "brep" facesCount = obj.Faces.Count if facesCount > 1: # inputted polysurface nameplateDCpowerRating = srfArea = activeArea = PVsurfacePercent = moduleActiveAreaPercent = moduleEfficiency = lifetime = ACenergyPerHour = totalRadiationPerHour = cellTemperaturePerHour = embodiedEnergyPerM2 = embodiedCO2PerM2 = None validInputData = False printMsg = "The brep you supplied to \"_PVsurface\" is a polysurface. Please supply a surface" return nameplateDCpowerRating, srfArea, activeArea, PVsurfacePercent, moduleActiveAreaPercent, moduleEfficiency, lifetime, ACenergyPerHourData, totalRadiationPerHourData, cellTemperaturePerHourData, ACenergyDemandPerHourData, energyCostPerKWh, embodiedEnergyPerM2, embodiedCO2PerM2, gridEfficiency, locationName, validInputData, printMsg else: # inputted brep with a single surface srfArea = Rhino.Geometry.AreaMassProperties.Compute(obj).Area * (PVsurfacePercent/100) # in m2 srfArea = srfArea * unitConversionFactor # in m2 activeArea = srfArea * (moduleActiveAreaPercent/100) # in m2 nameplateDCpowerRating = activeArea * (1 * (moduleEfficiency/100)) # in kW validInputData = True printMsg = "ok" return nameplateDCpowerRating, srfArea, activeArea, PVsurfacePercent, moduleActiveAreaPercent, moduleEfficiency, lifetime, ACenergyPerHourData, totalRadiationPerHourData, cellTemperaturePerHourData, ACenergyDemandPerHourData, energyCostPerKWh, embodiedEnergyPerM2, embodiedCO2PerM2, gridEfficiency, locationName, validInputData, printMsg else: PVsurfaceInputType = "number" try: # input is number (pv surface area in m2) srfArea = float(PVsurface) * (PVsurfacePercent/100) # in m2 srfArea = srfArea * unitConversionFactor # in m2 activeArea = srfArea * (moduleActiveAreaPercent/100) # in m2 nameplateDCpowerRating = activeArea * (1 * (moduleEfficiency/100)) # in kW validInputData = True printMsg = "ok" return nameplateDCpowerRating, srfArea, activeArea, PVsurfacePercent, moduleActiveAreaPercent, moduleEfficiency, lifetime, ACenergyPerHourData, totalRadiationPerHourData, cellTemperaturePerHourData, ACenergyDemandPerHourData, energyCostPerKWh, embodiedEnergyPerM2, embodiedCO2PerM2, gridEfficiency, locationName, validInputData, printMsg except Exception, e: pass # input is string (nameplateDCpowerRating in kW) lowerString = PVsurface.lower() if "kw" in lowerString: nameplateDCpowerRating = float(lowerString.replace("kw","")) * (PVsurfacePercent/100) # in kW activeArea = nameplateDCpowerRating / (1 * (moduleEfficiency/100)) # in m2 srfArea = activeArea * (100/moduleActiveAreaPercent) # in m2 validInputData = True printMsg = "ok" return nameplateDCpowerRating, srfArea, activeArea, PVsurfacePercent, moduleActiveAreaPercent, moduleEfficiency, lifetime, ACenergyPerHourData, totalRadiationPerHourData, cellTemperaturePerHourData, ACenergyDemandPerHourData, energyCostPerKWh, embodiedEnergyPerM2, embodiedCO2PerM2, gridEfficiency, locationName, validInputData, printMsg else: nameplateDCpowerRating = srfArea = activeArea = PVsurfacePercent = moduleActiveAreaPercent = moduleEfficiency = lifetime = ACenergyPerHour = totalRadiationPerHour = cellTemperaturePerHour = embodiedEnergyPerM2 = embodiedCO2PerM2 = None validInputData = False printMsg = "Something is wrong with your \"PVsurface\" input data" return nameplateDCpowerRating, srfArea, activeArea, PVsurfacePercent, moduleActiveAreaPercent, moduleEfficiency, lifetime, ACenergyPerHourData, totalRadiationPerHourData, cellTemperaturePerHourData, ACenergyDemandPerHourData, energyCostPerKWh, embodiedEnergyPerM2, embodiedCO2PerM2, gridEfficiency, locationName, validInputData, printMsg
def checkInputData(geometryIds, numOfInitialPts, initialPtsSpread, stepSize, flowPathsType): # check inputs if len(geometryIds) == 0: geometryMesh = numOfInitialPts = initialPtsSpread = initialPtsSpreadLabel = stepSize = flowPathsType = flowPathsTypeLabel = None validInputData = False printMsg = "\"_geometry\" input is empty.\n" + \ "Please supply a surface and/or polysurface and/or mesh for which you would like to conduct the flow path analysis (that can be a building, terrain, landscape or any other sort of geometry)." return geometryMesh, numOfInitialPts, initialPtsSpread, initialPtsSpreadLabel, stepSize, flowPathsType, flowPathsTypeLabel, validInputData, printMsg if (numOfInitialPts == None): numOfInitialPts = 100 # default elif (numOfInitialPts < 2): print "\"numOfInitialPts_\" input can not be less than 2.\n" + \ "\"numOfInitialPts_\" input set to 2." numOfInitialPts = 2 if (initialPtsSpread == None): initialPtsSpread = 1 # default (Random) initialPtsSpreadLabel = "Random" if (initialPtsSpread == 0): initialPtsSpreadLabel = "Rectangular grid" elif (initialPtsSpread == 1): initialPtsSpreadLabel = "Random" else: print "\"initialPtsSpread_\" input only accepts values: 0 (Rectangular grid) and 1 (Random).\n" + \ "\"initialPtsSpread_\" input set to 1 (Random)." initialPtsSpread = 1 initialPtsSpreadLabel = "Random" if (stepSize == None): stepSize = 1 # default (in rhino document units) elif (stepSize < 0.01): print "\"stepSize_\" input only accepts values larger 0.01 rhino document units (meters, feet, inches...).\n" + \ "\"stepSize_\" input set to 1 rhino document unit." stepSize = 1 if (flowPathsType == None): flowPathsType = 0 # default (polylines) flowPathsTypeLabel = "Polylines" if (flowPathsType == 0): flowPathsTypeLabel = "Polylines" elif (flowPathsType == 1): flowPathsTypeLabel = "Curves" else: print "\"flowPathsType_\" input only accepts values: 0 (Polylines) and 1 (Curves).\n" + \ "\"flowPathsType_\" input set to 0 (Polylines)." flowPathsType = 0 flowPathsTypeLabel = "Polylines" # create a geometryMesh from _geometry inputs geometryMesh = Rhino.Geometry.Mesh( ) # joined mesh of all geometry supplied into the "_geometry" input geometryObjs = [ rs.coercegeometry(geometryId) for geometryId in geometryIds ] for geometryObj in geometryObjs: if isinstance(geometryObj, Rhino.Geometry.Mesh): geometryMesh.Append(geometryObj) elif isinstance(geometryObj, Rhino.Geometry.Brep): meshParam = Rhino.Geometry.MeshingParameters() #meshParam.MaximumEdgeLength = maxEdgeLength_ # more beneficial for drainage area per flow direction meshParam.SimplePlanes = True meshesFromBrep = Rhino.Geometry.Mesh.CreateFromBrep( geometryObj, meshParam) for mesh in meshesFromBrep: geometryMesh.Append(mesh) if geometryMesh.IsValid == True: # a brep and/or a mesh supplied to "_geometry" input pass else: # neither mesh nor brep object(s) have been supplied into the "_geometry" input geometryMesh = numOfInitialPts = initialPtsSpread = initialPtsSpreadLabel = stepSize = flowPathsType = flowPathsTypeLabel = None validInputData = False printMsg = "The data you supplied to the \"_geometry\" input is neither a surface and/or polysurface and/or mesh.\n" + \ "Please input some (or all) of these types of data to the \"_geometry\" input." return geometryMesh, numOfInitialPts, initialPtsSpread, initialPtsSpreadLabel, stepSize, flowPathsType, flowPathsTypeLabel, validInputData, printMsg validInputData = True printMsg = "ok" return geometryMesh, numOfInitialPts, initialPtsSpread, initialPtsSpreadLabel, stepSize, flowPathsType, flowPathsTypeLabel, validInputData, printMsg
import copy import scriptcontext as sc import rhinoscriptsyntax as rs import clr Grammar = sc.sticky["Grammar"] clr.AddReference("Grasshopper") from Grasshopper.Kernel.Data import GH_Path from Grasshopper import DataTree if run: if court_ref: G = Grammar() type_info = G.helper_get_type(court_ref) if type_info == "geometry": court_ref = rs.coercegeometry(court_ref) rule = DataTree[object]() rule_ = [\ ['court', True],\ ['grammar_key','court'],\ ['court_width', width],\ ['court_node', -1],\ ['court_slice', True],\ ['court_randomize',randomize],\ ['court_cut_width',cut_width],\ ['court_ref', court_ref],\ ['end_rule']] for i, r in enumerate(rule_): rule.Add(r)