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): self.particles = [] self.targetID = r'8d8dd842-3d3f-4f65-b7d4-e4089e4f9cbb' self.target = rs.coercemesh(self.targetID) self.boundary = rg.Box(rg.Plane.WorldXY, rg.Interval(0, 100), rg.Interval(0, 100), rg.Interval(0, 100)) self.boundary = self.boundary.ToBrep() self.time = 0 self.attr = rc.DocObjects.ObjectAttributes() self.attr.ColorSource = rc.DocObjects.ObjectColorSource.ColorFromObject self.attr.MaterialSource = rc.DocObjects.ObjectMaterialSource.MaterialFromObject grad = color.GetGradient(1) self.attr.ObjectColor = color.GradientOfColors(grad, 0) self.attr.ObjectColor = drawing.Color.White index = sc.doc.Materials.Add() self.mat = sc.doc.Materials[index] self.mat.DiffuseColor = self.attr.ObjectColor self.mat.CommitChanges() self.attr.MaterialIndex = index self.attr = rc.DocObjects.ObjectAttributes() self.attr.ColorSource = rc.DocObjects.ObjectColorSource.ColorFromObject self.attr.MaterialSource = rc.DocObjects.ObjectMaterialSource.MaterialFromObject #ATTR1 self.attr1 = rc.DocObjects.ObjectAttributes() self.attr1.ColorSource = rc.DocObjects.ObjectColorSource.ColorFromObject self.attr1.MaterialSource = rc.DocObjects.ObjectMaterialSource.MaterialFromObject self.attr1.ObjectColor = drawing.Color.Green index = sc.doc.Materials.Add() mat1 = sc.doc.Materials[index] mat1.DiffuseColor = self.attr1.ObjectColor mat1.CommitChanges() self.attr1.MaterialIndex = index #ATTR2 self.attr2 = rc.DocObjects.ObjectAttributes() self.attr2.ColorSource = rc.DocObjects.ObjectColorSource.ColorFromObject self.attr2.MaterialSource = rc.DocObjects.ObjectMaterialSource.MaterialFromObject self.attr2.ObjectColor = drawing.Color.Blue index = sc.doc.Materials.Add() mat2 = sc.doc.Materials[index] mat2.DiffuseColor = self.attr2.ObjectColor mat2.CommitChanges() self.attr2.MaterialIndex = index self.clays = [] #numClays = 1 #for i in range(numClays): # self.clays.append(Clay(self, color.GradientOfColors(grad, i/numClays), rg.Interval(25+(i*10), 35+(i*10)))) numClays = 1 self.clays.append( Clay(self, color.GradientOfColors(grad, 0), rg.Interval(35, 65))) self.particles = [] for i in range(6): self.particles.append(Particle(self))
def _get_building_member_info(self, gripping_config): start = timer() if self.debug else None self.simulator.set_robot_config(self.robot, gripping_config) mesh = mesh_from_guid(Mesh, self.building_member) handle = self.simulator.add_building_member(self.robot, mesh) matrix = self.simulator.get_object_matrices([handle])[handle] parent_handle = self.simulator.get_object_handle('customGripper' + self.robot.name) _, _, mesh_matrix, _, _ = self.simulator.run_child_script( 'getShapeMatrixRelative', [handle, parent_handle], [], []) relative_transform = _to_xform(mesh_matrix) transform = _to_xform(matrix) mesh_at_origin = _transform_to_origin( rs.coercemesh(self.building_member), transform) if self.debug: LOG.debug('Execution time: building member=%.2f', timer() - start) return { 'mesh': mesh_at_origin, 'parent_handle': parent_handle, 'relative_transform': relative_transform }
def Bulge(): input_mesh_id = rs.GetObjects("Select model mesh", 32, True, False) if not input_mesh_id: return cutter_mesh_id = rs.GetObjects("Select mesh defining bottom of bulge", 32, True, False, False) if not cutter_mesh_id: return bulge_height = rs.GetReal("Enter bulge chamber height", 5.0, 1.0) if not bulge_height: return input_mesh = rs.coercemesh(input_mesh_id, True) offset_mesh = input_mesh.Offset(0.5) input_brep = Rhino.Geometry.Brep.CreateFromMesh(offset_mesh, False) cutter_mesh = rs.coercemesh(cutter_mesh_id, True) cutter_brep = Rhino.Geometry.Brep.CreateFromMesh(cutter_mesh, False) offset_cutter_meshes = Rhino.Geometry.Mesh.Offset(cutter_mesh, bulge_height, True) cutter_brep = Rhino.Geometry.Brep.CreateFromMesh(offset_cutter_meshes, False) brep_pieces = Rhino.Geometry.Brep.Split(input_brep, cutter_brep, 0.01) inner_chamber_brep = brep_pieces[ 2] # may need to manually change this index for some models/cuts scriptcontext.doc.Objects.AddBrep(inner_chamber_brep) inner_chamber_mesh = Rhino.Geometry.Mesh() mesh_array = Rhino.Geometry.Mesh.CreateFromBrep(inner_chamber_brep) for mesh in mesh_array: inner_chamber_mesh.Append(mesh) inner_chamber_mesh.FillHoles() scriptcontext.doc.Objects.AddMesh(inner_chamber_mesh) # TEM mesh inner_chamber_mesh.Flip(True, True, True) inner_chamber_mesh.Append(input_mesh) scriptcontext.doc.Objects.AddMesh(inner_chamber_mesh) # main material mesh #for brep_piece in inner_chamber[0]: # scriptcontext.doc.Objects.AddBrep(brep_piece) #doc.Objects.Delete(obj_ref, False) scriptcontext.doc.Views.Redraw() return Rhino.Commands.Result.Success
def mesh_to_mesh(rhino_mesh,trg_len,vis): print rhino_mesh crvs = rs.DuplicateMeshBorder(rhino_mesh) vertices = [map(float, vertex) for vertex in rs.MeshVertices(rhino_mesh)] faces = map(list, rs.MeshFaceVertices(rhino_mesh)) mesh = Mesh.from_vertices_and_faces(vertices, faces) pts_objs = rs.GetObjects("Fixed Points",1) rs.EnableRedraw(False) if pts_objs: pts_fixed = [rs.PointCoordinates(obj) for obj in pts_objs] pts = [] index_key = {} count = 0 for k, a in mesh.vertices_iter(True): pts.append((a['x'], a['y'], a['z'])) index_key[count] = k count += 1 fixed = [] for pt_fix in pts_fixed: index = rs.PointArrayClosestPoint(pts,pt_fix) fixed.append(index_key[index]) edge_lengths = [] for u, v in mesh.edges(): edge_lengths.append(mesh.edge_length(u, v)) target_start = max(edge_lengths)/2 id = rs.coerceguid(rhino_mesh, True) mesh_rhino_obj = rs.coercemesh(id, False) boundary = set(mesh.vertices_on_boundary()) user_func = wrapper_2(crvs,mesh_rhino_obj,fixed,boundary,vis) rs.HideObject(rhino_mesh) remesh(mesh,trg_len, tol=0.1, divergence=0.01, kmax=400, target_start=target_start, kmax_approach=200, verbose=False, allow_boundary=True, ufunc=user_func) rs.DeleteObject(rhino_mesh) return draw_light(mesh,temp = False)
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 mesh_from_guid(guid, **kwargs): """Creates an instance of a compAS mesh class from an identifier in Rhino/Grasshopper. This function is almost identical to ``mesh_from_guid`` in the core framework, but there were some import issues when used from within Grasshopper, but eventually, it should be migrated into the core. """ trimesh = ghcomp.Triangulate(rs.coercemesh(guid))[0] vertices = [map(float, vertex) for vertex in rs.MeshVertices(trimesh)] faces = map(list, rs.MeshFaceVertices(trimesh)) faces = [face[:-1] if face[-2] == face[-1] else face for face in faces] mesh = Mesh.from_vertices_and_faces(vertices, faces) mesh.attributes.update(kwargs) return mesh
def __init__(self): self.attr = util.BasicAttr() self.headID = r'941e5133-6d8f-4a2a-853f-f4d3588c3b95' self.mesh = rs.coercemesh(self.headID) self.pn = perlin.SimplexNoise() pt = rg.Point3d(10,60,80) vec = rg.Vector3d(0,-10, 10) plane = rg.Plane(pt, vec) xint = rg.Interval(0, 80) yint = rg.Interval(0, 80) xcount = 10 ycount = 10 #self.mesh = rg.Mesh.CreateFromPlane(plane, xint, yint, xcount, ycount) #self.meshOrig = self.mesh.Duplicate() if False: for i, v in enumerate(self.mesh.Vertices): val = self.pn.noise2(util.Remap(v.X, 10, 90, 0, 3), util.Remap(v.Y, 0, 50, 0, 3)) vec = self.meshOrig.Normals[i] vec = rg.Vector3d(vec) vec *= val * 20 xform = rg.Transform.Translation(vec) v.Transform(xform) self.mesh.Vertices[i] = v for i, v in enumerate(self.mesh.Vertices): val = self.pn.noise3(util.Remap(v.X, 10, 90, 0, 1), util.Remap(v.Y, 0, 50, 0, 1), 0) vec = self.meshOrig.Normals[i] vec = rg.Vector3d(vec) vec *= val * 30 xform = rg.Transform.Translation(vec) v.Transform(xform) self.mesh.Vertices[i] = v for i, v in enumerate(self.mesh.Vertices): rand = geo.RandomVector3d(4) self.mesh.Vertices[i] += rg.Vector3f(rand.X, rand.Y, rand.Z) self.vObjects = [] for i, v in enumerate(self.mesh.Vertices): self.vObjects.append(vObject(self, v, i)) self.meshID = None
def get_mesh(self, prompt="select a mesh", triangulate=False): mesh_id = rs.GetObject(prompt, 32, True) rh_mesh = rs.coercemesh(mesh_id) verts = [Point(rh_pt.X,rh_pt.Y,rh_pt.Z) for rh_pt in rh_mesh.Vertices] faces = [] for rh_fc in rh_mesh.Faces : if triangulate: faces.append([rh_fc[0],rh_fc[1],rh_fc[2]]) #add the first three points of each face if rh_fc[2] != rh_fc[3] : faces.append([rh_fc[0],rh_fc[2],rh_fc[3]]) #if face is a quad, add the missing triangle else : if rh_fc[2] == rh_fc[3] : faces.append([rh_fc[0],rh_fc[1],rh_fc[2]]) else : faces.append([rh_fc[0],rh_fc[1],rh_fc[2],rh_fc[3]]) return Mesh(verts,faces)
def AgiImport(dirpath, file): """ Create new rhino file, import mesh, split, then save. """ objPath = dirpath + '\\' + file if os.path.exists(objPath) == False: print objPath return ## Open new template file ## template = rs.TemplateFile() cmd = "-_New " cmd += template + " " rs.Command(cmd) cmd = "-_Import " cmd += '"' + os.path.abspath(objPath) + '"' + " " cmd += "IgnoreTextures=No " cmd += "MapOBJToRhinoZ=Yes " cmd += "_Enter " rs.Command(cmd) rs.Command("SplitDisjointMesh ") meshes = rs.LastCreatedObjects() max = 0 keep = None for guid in meshes: mesh = rs.coercemesh(guid) count = mesh.Faces.Count if count > max: keep = guid max = count if keep: meshes.remove(keep) rs.DeleteObjects(meshes) rs.ZoomExtents(all=True) cmd = "-_SaveAs " cmd += "SaveTextures=Yes " cmd += '"' + os.path.abspath(objPath).replace(".obj", ".3dm") + '"' + " " cmd += "_Enter " rs.Command(cmd) rs.DocumentModified(False) Rhino.RhinoApp.Wait()
def GetMeshVertices(mesh_guid): #coerce the mesh_guid mesh_objref = rs.coercemesh(mesh_guid) #create a list to hold a list of vertices per face mesh_faces = [] #get the faces of the mesh for index in range(mesh_objref.Faces.Count): #get the vertices of the face at the current index face_vertices = mesh_objref.Faces.GetFaceVertices(index) #if the vertices of the face were returned > the element at the first index will be a True boolean if (face_vertices[0] and face_vertices[3] == face_vertices[4]): mesh_faces.append( [face_vertices[1], face_vertices[2], face_vertices[3]]) #if the mesh_faces has elements equal to the faces of the mesh if (len(mesh_faces) == mesh_objref.Faces.Count): #return the list of mesh faces return mesh_faces
def IntersectMeshPlane(obj, plane): tolerance = rs.UnitAbsoluteTolerance() #BREP mesh = rs.coercemesh(obj) intersectionCrvs = [] if mesh is None: return None x = rc.Geometry.Intersect.Intersection.MeshPlane(mesh, plane) if x is None: return #Match attributes finalCurves = [] for curve in x: finalCurve = sc.doc.Objects.AddPolyline(curve) utils.SafeMatchObjectAttributes(finalCurve, obj) #rs.MatchObjectAttributes(finalCurve, obj) BROKEN finalCurves.append(finalCurve) return finalCurves
def __init__(self): self.headID = r'941e5133-6d8f-4a2a-853f-f4d3588c3b95' self.head = rs.coercemesh(self.headID) bb = self.head.GetBoundingBox(rg.Plane.WorldXY) yscale = 1 / bb.Max.Y zscale = 1 / bb.Max.Z xform = rg.Transform.Scale(rg.Plane.WorldXY, 1, yscale, 1) self.head.Transform(xform) self.pn = perlin.SimplexNoise() pt = rg.Point3d(10, 60, 80) vec = rg.Vector3d(0, -10, 10) plane = rg.Plane(pt, vec) xint = rg.Interval(0, 80) yint = rg.Interval(0, 80) xcount = 10 ycount = 10 self.mesh = rg.Mesh.CreateFromPlane(plane, xint, yint, xcount, ycount) self.meshOrig = self.mesh.Duplicate() for i, v in enumerate(self.mesh.Vertices): val = self.pn.noise2(util.Remap(v.X, 10, 90, 0, 3), util.Remap(v.Y, 0, 50, 0, 3)) vec = self.meshOrig.Normals[i] vec = rg.Vector3d(vec) vec *= val * 8 xform = rg.Transform.Translation(vec) v.Transform(xform) self.mesh.Vertices[i] = v for i, v in enumerate(self.mesh.Vertices): val = self.pn.noise3(util.Remap(v.X, 10, 90, 0, 1), util.Remap(v.Y, 0, 50, 0, 1), 0) vec = self.meshOrig.Normals[i] vec = rg.Vector3d(vec) vec *= val * 20 xform = rg.Transform.Translation(vec) v.Transform(xform) self.mesh.Vertices[i] = v self.meshID = None self.headsID = None
def RunSearch(): id = rs.GetObject("select mesh", rs.filter.mesh) mesh = rs.coercemesh(id) if mesh: rs.UnselectObject(id) tree = Rhino.Geometry.RTree() # I can add a RhinoCommon function that just builds an rtree from the # vertices in one quick shot, but for now... for i,vertex in enumerate(mesh.Vertices): tree.Insert(vertex, i) while(True): point = rs.GetPoint("test point") if not point: break data = SearchData(mesh, point) # Use the first vertex in the mesh to define a start sphere distance = point.DistanceTo(mesh.Vertices[0]) sphere = Rhino.Geometry.Sphere(point, distance * 1.1) if tree.Search(sphere, SearchCallback, data): rs.AddPoint(mesh.Vertices[data.Index]) print "Found point in {0} tests".format(data.HitCount)
def RunSearch(): id = rs.GetObject("select mesh", rs.filter.mesh) mesh = rs.coercemesh(id) if mesh: rs.UnselectObject(id) tree = Rhino.Geometry.RTree() # I can add a RhinoCommon function that just builds an rtree from the # vertices in one quick shot, but for now... for i, vertex in enumerate(mesh.Vertices): tree.Insert(vertex, i) while (True): point = rs.GetPoint("test point") if not point: break data = SearchData(mesh, point) # Use the first vertex in the mesh to define a start sphere distance = point.DistanceTo(mesh.Vertices[0]) sphere = Rhino.Geometry.Sphere(point, distance * 1.1) if tree.Search(sphere, SearchCallback, data): rs.AddPoint(mesh.Vertices[data.Index]) print "Found point in {0} tests".format(data.HitCount)
def get_mesh(self, prompt="select a mesh", triangulate=False): mesh_id = rs.GetObject(prompt, 32, True) rh_mesh = rs.coercemesh(mesh_id) verts = [ Point(rh_pt.X, rh_pt.Y, rh_pt.Z) for rh_pt in rh_mesh.Vertices ] faces = [] for rh_fc in rh_mesh.Faces: if triangulate: faces.append([rh_fc[0], rh_fc[1], rh_fc[2] ]) #add the first three points of each face if rh_fc[2] != rh_fc[3]: faces.append([ rh_fc[0], rh_fc[2], rh_fc[3] ]) #if face is a quad, add the missing triangle else: if rh_fc[2] == rh_fc[3]: faces.append([rh_fc[0], rh_fc[1], rh_fc[2]]) else: faces.append([rh_fc[0], rh_fc[1], rh_fc[2], rh_fc[3]]) return Mesh(verts, faces)
meshes.append(mesh2) #side_3 test box3 = Box(side_2,100,50,100) mesh3 = Mesh.from_vertices_and_faces(box3.vertices, box3.faces) meshes.append(mesh3) #side_4 test box4 = Box(side_3,100,50,100) mesh4 = Mesh.from_vertices_and_faces(box4.vertices, box4.faces) meshes.append(mesh4) ####tests for point projection test = Get_PointOnCurve("select point") Obj_ref = rs.GetObject(message = "select mesh(es)", filter = 32, preselect = False, subobjects = True) mesh_test = rs.coercemesh(Obj_ref) print(test) dir_vec = Rhino.Geometry.Vector3d(box.frame.xaxis.x,box.frame.xaxis.y,box.frame.xaxis.z) print(type(dir_vec)) ray = Rhino.Geometry.Ray3d(test, dir_vec) #needs to be fed as rhino vector lineLength = Rhino.Geometry.Intersect.Intersection.MeshRay(mesh_test,ray) print(test) # # ###artist = MeshArtist(None, layer='Beams_out') ###artist.clear_layer() ###for mesh in meshes: ##artist = MeshArtist(mesh1, layer='Beams_out') ##artist.clear_layer() ##artist.draw_faces(join_faces=True)
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 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)
fm = Mesh() for p in left: fm.Vertices.Add(p) fm.Faces.AddFace(*range(len(left))) return fm else: left.append(left[0]) poly = Polyline(left) fm = Rhino.Geometry.Mesh.CreateFromClosedPolyline(poly) return fm return None #f=m.Faces[0] #split_mesh_face(f,plane) k = rs.GetObject('sel') m = rs.coercemesh(k) plane = rs.WorldZXPlane() m = mesh_plane_trim(m, plane, reverse=True) Rhino.RhinoDoc.ActiveDoc.Objects.AddMesh(m) Rhino.RhinoDoc.ActiveDoc.Views.Redraw() # #ngons=m.Ngons #tvs=m.TopologyVertices #for i in range(len(tvs)): # rs.AddTextDot(i,tvs[i]) # print(i)
def point_on_plane_top(pt, plane): testVect = plane.XAxis if plane.XAxis.Z != 0: testVect = plane.YAxis pp1 = plane.Origin pp2 = pp1 + testVect v1 = pp1 - pt v2 = pp2 - pt n = rs.VectorCrossProduct(v1, v2) return n.Z > 0 guid = rs.GetObject('sel') mesh = rs.coercemesh(guid) print(mesh) plane = rs.WorldZXPlane() print(plane) print(plane.ZAxis) #intersect pls = Rhino.Geometry.Intersect.Intersection.MeshPlane(mesh, plane) for pl in pls: for i in range(len(pl)): p = pl[i] rs.AddTextDot(i, p) rs.AddPolyline(pl) Rhino.Geometry.Mesh.Faces
import rhinoscriptsyntax as rs import Rhino import math #www.github.com/mcneel/rhinopyton/blob/master/scripts/rhinoscript/mesh.py #phyton tutorial mesh_id = rs.GetObject("Selecteer een mesh") if(mesh_id != None): mesh = rs.coercemesh(mesh_id) polygons = rs.MeshFaces(mesh,True) vertices = rs.MeshVertices(mesh) print vertices print len(polygons) print min(vertices) print max(vertices) minVertex = [vertices[0][0], vertices[0][1], vertices[0][2]] maxVertex = [vertices[0][0], vertices[0][1], vertices[0][2]] for vertex in vertices: if vertex[0] < minVertex[0]: minVertex[0] = vertex[0] elif vertex[0] > maxVertex[0]: maxVertex[0] = vertex[0] if vertex[1] < minVertex[1]: minVertex[1] = vertex[1] elif vertex[1] > maxVertex[1]: maxVertex[1] = vertex[1] if vertex[2] < minVertex[2]:
def MeshTextureCoordinates(object_id): meshObj = rs.coercemesh(object_id) mCoordL = [] for i in range(meshObj.TextureCoordinates.Count): mCoordL.append(meshObj.TextureCoordinates[i]) return mCoordL