def TestIntersection(obj, tester): # there are a few possible intersection methods in rhinoscriptsyntax # as an initial setup only a few intersections are handled # to make this script faster and more robuste best would be to intersect not with rhinoscriptsyntax # But use RhinoCommon methods instead. # #for now only rhinoscriptsyntax methods are used as an example below: # if both are breps ( (poly)surface or extrusion if rs.IsBrep(obj) and rs.IsBrep(tester): intersections = rs.IntersectBreps(obj, tester) if intersections: #Delete intersections if they were made rs.DeleteObjects(intersections) return True if rs.IsMesh(obj) and rs.IsMesh(tester): intersections = rs.MeshMeshIntersection(obj, tester) if intersections: #This method does not create a curve but returns a list of points #so nothing to delete return True #Mixed input needs to be handled different as is with curves. #if either is a mesh the other needs to be converted to a mesh as well #catchall return False return False
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 add_element_set(structure, guids, name): """ Adds element set information from Rhino curve and mesh guids. Parameters ---------- structure : obj Structure object to update. guids : list Rhino curve and Rhino mesh guids. name : str Name of the new element set. Returns ------- None Notes ----- - Meshes representing solids must have 'solid' in their name. """ elements = [] for guid in guids: if rs.IsCurve(guid): sp = structure.check_node_exists(rs.CurveStartPoint(guid)) ep = structure.check_node_exists(rs.CurveEndPoint(guid)) element = structure.check_element_exists([sp, ep]) if element is not None: elements.append(element) if rs.IsMesh(guid): vertices = rs.MeshVertices(guid) faces = rs.MeshFaceVertices(guid) if 'solid' in rs.ObjectName(guid): nodes = [structure.check_node_exists(i) for i in vertices] element = structure.check_element_exists(nodes) if element is not None: elements.append(element) else: for face in faces: nodes = [ structure.check_node_exists(vertices[i]) for i in face ] if nodes[2] == nodes[3]: nodes = nodes[:-1] element = structure.check_element_exists(nodes) if element is not None: elements.append(element) structure.add_set(name=name, type='element', selection=elements)
def DropBlockToSurface(): try: obj = rs.GetObjects('Select Objects', rs.filter.curve | rs.filter.instance | rs.filter.mesh | rs.filter.surface | rs.filter.subd | rs.filter.light | rs.filter.polysurface, preselect=True) srf = rs.GetObject('Select Surface') if obj: if srf: rs.EnableRedraw(False) # Check if srf is a mesh, if so convert to Nurb isMesh = rs.IsMesh(srf) if isMesh == True: srf = rs.MeshToNurb(srf) # For each object send test rays up and down in Z coord # Move each object to the ray test that hits a srf for i in obj: bndBox = rs.BoundingBox(i) pt1 = bndBox[0] pt2 = bndBox[2] crv = rs.AddLine(pt1, pt2) if crv: midcrv = rs.CurveMidPoint(crv) rs.DeleteObject(crv) ray_pt_up = rs.ShootRay(srf, midcrv, (0, 0, 1), reflections=1) ray_pt_down = rs.ShootRay(srf, midcrv, (0, 0, -1), reflections=1) if ray_pt_up: vector = rs.VectorCreate(ray_pt_up[1], midcrv) rs.MoveObject(i, vector) if ray_pt_down: vector = rs.VectorCreate(ray_pt_down[1], midcrv) rs.MoveObject(i, vector) # deleate any created srf if isMesh == True: rs.DeleteObject(srf) rs.EnableRedraw(True) except: print("Failed to execute") rs.EnableRedraw(True) return
def clean_and_coerce_list(brep_list): #""" Ladybug - This definition cleans the list and adds them to RhinoCommon""" outputMesh = [] outputBrep = [] for id in brep_list: if rs.IsMesh(id): geo = rs.coercemesh(id) if geo is not None: outputMesh.append(geo) try: rs.DeleteObject(id) except: pass elif rs.IsBrep(id): geo = rs.coercebrep(id) if geo is not None: outputBrep.append(geo) try: rs.DeleteObject(id) except: pass else: # the idea was to remove the problematice surfaces # not all the geometry which is not possible since # badGeometries won't pass rs.IsBrep() tempBrep = [] surfaces = rs.ExplodePolysurfaces(id) for surface in surfaces: geo = rs.coercesurface(surface) if geo is not None: tempBrep.append(geo) try: rs.DeleteObject(surface) except: pass geo = JoinBreps(tempBrep, 0.01) for Brep in tempBrep: Brep.Dispose() try: rs.DeleteObject(id) except: pass outputBrep.append(geo) return outputMesh, outputBrep
def IntersectGeo(obj, level): tolerance = rs.UnitAbsoluteTolerance() plane = rc.Geometry.Plane(rs.coerce3dpoint((0, 0, level)), rs.coerce3dvector((0, 0, 1))) finalCurves = [] #BLOCKS if rs.IsBlockInstance(obj): matrix = rs.BlockInstanceXform(obj) blockObjs = rs.BlockObjects(rs.BlockInstanceName(obj)) for eachBlockObj in blockObjs: newCopy = rs.CopyObject(eachBlockObj) xformedObj = rs.TransformObject(newCopy, matrix) #EXTRUSIONS if isinstance(xformedObj, rc.Geometry.Extrusion): temp = sc.doc.Objects.AddBrep(xformedObj.ToBrep(False)) xformedObj = rs.coercebrep(temp) rs.DeleteObject(temp) #BREPS IN BLOCK result = IntersectBrepPlane(xformedObj, plane) if result is None: continue for each in result: if each is not None: finalCurves.append(each) rs.DeleteObject(xformedObj) #MESHES IN BLOCK <---This code might not be necessary result = IntersectMeshPlane(xformedObj, plane) if result is None: continue for each in result: if each is not None: finalCurves.append(each) rs.DeleteObject(xformedObj) #BREPS elif rs.IsBrep(obj): result = IntersectBrepPlane(obj, plane) if result is None: return None for each in result: if each is not None: finalCurves.append(each) #MESHES elif rs.IsMesh(obj): result = IntersectMeshPlane(obj, plane) if result is None: return None for each in result: if each is not None: finalCurves.append(each) return finalCurves
def setAdditiveObj(self): #set object to be additived #if selected obj isnt closed, return False tmp = rs.GetObject("Select object which you want additive") #adapt to unclosed polysurface if rs.IsMesh(tmp): self.addtiveObj = rs.MeshToNurb(tmp) elif rs.IsPolysurface(tmp): self.addtiveObj = tmp else: print("please select \"mesh\" or \"polysurface\"") return True
def VolumeLiters(): """Report the volume in Litres of closed surfaces, polysurfaces, or meshes.""" input_obj = rs.SelectedObjects() if not input_obj: input_obj = rs.GetObjects("Select objects") if not input_obj: return volume = 0.0 for o in input_obj: if rs.IsMesh(o): a, b, c = rs.MeshVolume(o) volume += b elif rs.IsObjectSolid(o): a, b = rs.SurfaceVolume(o) volume += a if volume == 0.0: return volume = round(volume / (rs.UnitScale(rs.UnitSystem(), 3) * 10)**3, 3) print "Volume = {} liters".format(volume)
def on_click_add_hb_object(self, sender, e): objects = sc.doc.Objects.GetSelectedObjects(False, False) for obj in objects: if not rs.IsBrep(obj.Id) and not rs.IsMesh(obj.Id): return #check object on list if obj.Id in self.m_hb_object_ids: return #create grid item row itemText = obj.ShortDescription(False) if obj.Name: itemText += " - " + obj.Name self.m_hb_object_ids += [obj.Id] datarow = [itemText, self.m_hb_type_items, self.m_hb_material_items] #update grid values self.m_hb_objects_gridview.DataStore += \ [RowValues(datarow, self.m_hb_column_cell_type)]
def add_element_set(structure, guids, name): added_ele = set() for guid in guids: if rs.IsMesh(guid): vertices = rs.MeshVertices(guid) faces = rs.MeshFaceVertices(guid) nodes = [structure.add_node(vertex) for vertex in vertices] for f in rs.MeshFaceVertices(guid): nodes = [structure.check_node_exists(vertices[i]) for i in f] if nodes[-1] == nodes[-2]: del nodes[-1] ekey = structure.add_element(nodes=nodes, type='ShellElement') if ekey is not None: added_ele.add(ekey) structure.add_set(name=name, type='element', selection=list(added_ele))
def lb_generate_test_points(self): try: #load breps/meshes from analysis grid object list brep_list = [] mesh_list = [] for item in self.m_gridsurfs_list_box.Items: if rs.IsBrep(item.Tag): brep_list += [Rhino.DocObjects.ObjRef(item.Tag).Brep()] elif rs.IsMesh(item.Tag): mesh_list += [Rhino.DocObjects.ObjRef(item.Tag).Mesh()] else: continue #prepare grid paramers grid_size = self.m_numeric_gridsize_updown.Value dist_base_surf = self.m_numeric_distsurf_updown.Value move_test_mesh = False #create meshes from breps, add to mesh list input_mesh = mesh_list + LadybugEto.createMesh(brep_list, grid_size) self.m_output_mesh = [] self.m_test_points = [] self.m_pts_vectors = [] for index, mesh in enumerate(input_mesh): test_points, pts_vectors, faces_area, output_mesh = \ LadybugEto.getTestPts( [mesh], dist_base_surf, move_test_mesh) self.m_test_points += [test_points] self.m_pts_vectors += [pts_vectors] self.m_output_mesh += output_mesh #update meshes in scene LadybugEto.bakeGeo(self.m_output_mesh, 'lb_sunlighthours') except Exception as e: print e
def on_click_add_grid_object(self, sender, e): objects = sc.doc.Objects.GetSelectedObjects(False, False) item_list = [item.Tag for item in self.m_gridsurfs_list_box.Items] for obj in objects: #invalid selection type? if not rs.IsBrep(obj.Id) and not rs.IsMesh(obj.Id): return #already in list? if obj.Id in item_list: return #create list item item = forms.ListItem() item.Text = obj.ShortDescription(False) if obj.Name: item.Text += " - " + obj.Name item.Tag = obj.Id self.m_gridsurfs_list_box.Items.Add(item) self.lb_generate_test_points()
def setAdditiveObj(self): ''' set object that is added when pick object, it must be mesh or polysurface if picked object is mesh, it will be converted to polysurface ''' tmp = rs.GetObject("Pick a additive obj", rs.filter.polysurface | rs.filter.mesh) if rs.IsMesh(tmp): self.additiveObj = rs.MeshToNurb(tmp) elif rs.IsPolysurface(tmp): self.additiveObj = tmp else: print("Please select \"mesh\" or \"polysurface\"") return False return True
def MeshObjects(self): ml_doc = [] objects = [rs.coercerhinoobject(o) for o in self.objects_to_render] for o in objects: obj_ref = Rhino.DocObjects.ObjRef(o) attr = obj_ref.Object().Attributes if attr.MaterialSource == Rhino.DocObjects.ObjectMaterialSource.MaterialFromLayer: layer = sc.doc.Layers[attr.LayerIndex] material_index = layer.RenderMaterialIndex else: material_index = attr.MaterialIndex if material_index == -1: attr.MaterialSource = Rhino.DocObjects.ObjectMaterialSource.MaterialFromObject attr.MaterialIndex = self.materials[0] #attr.CommitChanges() elif material_index not in self.materials: self.materials.append(material_index) if rs.IsMesh(o): ml_doc.append(sc.doc.Objects.AddMesh(o.MeshGeometry, attr)) continue p = o.GetRenderMeshParameters() obrefs = Rhino.DocObjects.RhinoObject.GetRenderMeshes([o], True, True) mainmesh = Rhino.Geometry.Mesh() for obref in obrefs: obm = obref.Mesh() mainmesh.Append(obm) ml_doc.append(sc.doc.Objects.AddMesh(mainmesh, attr)) rs.SelectObjects(ml_doc) return ml_doc
def MeshVtxAdjacentVtxs (strMesh, index, blnAbsolutConnections=False, blnCreate=False): """--------------------------------------------------------------------------------------------------------------------------------------- MeshVtxAdjacentVtxs finds the adjecent vertices on a mesh for a given index of a vertex. written by Ezio Blasetti. Last Revision 062411. Syntax MeshVtxAdjacentVtxs (strMesh, index, blnAbsolutConnections, blnCreate) Parameters strMesh Required. String. The identifier of a mesh object. index Required. Integer. The index of a vertex object inside the array returned from rs.MeshVertices method. Use rs.MeshVertexCount for the length of that array. blnAbsolutConnections Optional. Boolean. If True only the end points of the adjacent edges will be returned. Note, if false, all the vertices of the adjacent faces will be returned. blnCreate Optional. Boolean. Create the adjacent points. If false, points are not created. Returns Array If blnCreate is equal to True , an array containing 3D adjacent points if successful. Array If blnCreate is equal to False, an array containing the indexes of the adjacent vetrices if successful. None If not successful, or on error. Example import rhinoscriptsyntax as rs strObject = rs.GetObject("Select the mesh", 32) intRndVtxIndex = 0 arr = MeshVtxAdjacentVtxs (strObject, intRndVtxIndex, True, True) ---------------------------------------------------------------------------------------------------------------------------------------""" """custom function""" #----------------------------------------------------------------------------------------------------------------------------------------- def CullDuplicates(seq, idfun=None): # order preserving if idfun is None: def idfun(x): return x seen = {} result = [] for item in seq: marker = idfun(item) if marker in seen: continue seen[marker] = 1 result.append(item) return result #----------------------------------------------------------------------------------------------------------------------------------------- MeshVtxAdjacentVtxs = [] if rs.IsMesh(strMesh)==False : print "strMesh is not an mesh" return None if type(index)==type("string"): print "index is not an integer" return None if type(index)==type(0.1): index = int(index) arrVertices = rs.MeshVertices (strMesh) arrFaceVertices = rs.MeshFaceVertices(strMesh) intCount = 0 arrAdjacentVtxs = [] for arrFace in arrFaceVertices: blnIsAdjacent = False for arrVtxIndex in arrFace: if arrVtxIndex == index : blnIsAdjacent = True if blnIsAdjacent : if blnAbsolutConnections : if arrFace[2]==arrFace[3] : for arrVtxIndex in arrFace : if arrVtxIndex != index : arrAdjacentVtxs.append( arrVtxIndex) else : if index == arrFace[0] : arrAdjacentVtxs.append( arrFace[3] ) arrAdjacentVtxs.append( arrFace[1] ) elif index == arrFace[1] : arrAdjacentVtxs.append( arrFace[0] ) arrAdjacentVtxs.append( arrFace[2] ) elif index == arrFace[2] : arrAdjacentVtxs.append( arrFace[1] ) arrAdjacentVtxs.append( arrFace[3] ) elif index == arrFace(3) : arrAdjacentVtxs.append( arrFace[2] ) arrAdjacentVtxs.append( arrFace[0] ) else : for arrVtxIndex in arrFace : if arrVtxIndex != index : arrAdjacentVtxs.append( arrVtxIndex ) if type(arrAdjacentVtxs) != type([]) : return None arrOrderAdjacentVtxs = CullDuplicates(arrAdjacentVtxs) if blnCreate : arrStrPts = [] for arrVtxIndex in arrOrderAdjacentVtxs: rs.AddPoint ( arrVertices[arrVtxIndex] ) arrStrPts.append( arrVertices[arrVtxIndex] ) return arrStrPts else : return arrOrderAdjacentVtxs
def add_nodes_elements_from_layers(structure, layers, line_type=None, mesh_type=None, thermal=False, pA=None, pL=None): """ Adds node and element data from Rhino layers to the Structure object. Parameters ---------- structure : obj Structure object to update. layers : list Layer string names to extract nodes and elements. line_type : str Element type for line objects. mesh_type : str Element type for mesh objects. thermal : bool Thermal properties on or off. pA : float Mass area density [kg/m2]. pL : float Mass length density [kg/m]. Returns ------- list Node keys that were added to the Structure. list Element keys that were added to the Structure. """ if isinstance(layers, str): layers = [layers] added_nodes = set() added_elements = set() for layer in layers: elset = set() for guid in rs.ObjectsByLayer(layer): if line_type and rs.IsCurve(guid): sp_xyz = rs.CurveStartPoint(guid) ep_xyz = rs.CurveEndPoint(guid) ez = subtract_vectors(ep_xyz, sp_xyz) L = length_vector(ez) m = 0.5 * L * pL if pL else None sp = structure.add_node(xyz=sp_xyz, mass=m) ep = structure.add_node(xyz=ep_xyz, mass=m) added_nodes.add(sp) added_nodes.add(ep) try: name = rs.ObjectName(guid).replace("'", '"') if name[0] in ['_', '^']: name = name[1:] dic = json.loads(name) ex = dic.get('ex', None) ey = dic.get('ey', None) if ex and not ey: ey = cross_vectors(ex, ez) except: ex = None ey = None axes = {'ex': ex, 'ey': ey, 'ez': ez} ekey = structure.add_element(nodes=[sp, ep], type=line_type, thermal=thermal, axes=axes) if (line_type == 'BeamElement') and (ex is None): if (ez[0] == 0) and (ez[1] == 0): print( '***** WARNING: vertical BeamElement with no ex axis, element {0} *****' .format(ekey)) if ekey is not None: added_elements.add(ekey) elset.add(ekey) elif mesh_type and rs.IsMesh(guid): mesh = mesh_from_guid(Mesh(), guid) vertices = rs.MeshVertices(guid) nodes = [] masses = [] for c, vertex in enumerate(vertices): m = mesh.vertex_area(c) * pA if pA else None masses.append(m) nodes.append(structure.add_node(xyz=vertex, mass=m)) added_nodes.update(nodes) if mesh_type in [ 'HexahedronElement', 'TetrahedronElement', 'SolidElement', 'PentahedronElement' ]: ekey = structure.add_element(nodes=nodes, type=mesh_type, thermal=thermal) if ekey is not None: added_elements.add(ekey) elset.add(ekey) elif mesh_type == 'MassElement': nodei = 0 for node in nodes: ekey = structure.add_element(nodes=[node], type=mesh_type, thermal=thermal, mass=masses[nodei]) nodei += 1 if ekey is not None: added_elements.add(ekey) elset.add(ekey) else: try: name = rs.ObjectName(guid).replace("'", '"') if name[0] in ['_', '^']: name = name[1:] dic = json.loads(name) ex = dic.get('ex', None) ey = dic.get('ey', None) ez = dic.get('ez', None) if (ex and ey) and (not ez): ez = cross_vectors(ex, ey) except: ex = None ey = None ez = None axes = {'ex': ex, 'ey': ey, 'ez': ez} for face in rs.MeshFaceVertices(guid): nodes = [ structure.check_node_exists(vertices[i]) for i in face ] if nodes[-1] == nodes[-2]: del nodes[-1] ekey = structure.add_element(nodes=nodes, type=mesh_type, thermal=thermal, axes=axes) if ekey is not None: added_elements.add(ekey) elset.add(ekey) structure.add_set(name=layer, type='element', selection=list(elset)) return list(added_nodes), list(added_elements)
def generateAnalysis(test_points, pts_vectors, name, window_groups, sun_vectors, hoys, timestep, hb_object_ids, hb_object_types, hb_object_mats, folder, filename, save_file_only, grid_mesh): try: analysis_grids = AnalysisGrid.from_points_and_vectors( test_points, pts_vectors, name, window_groups) #get analysis recipe analysis_recipe = None if sun_vectors and sun_vectors[0] != None and \ hoys and hoys[0] != None and analysis_grids: # set a sunlight hours analysis recipe together if there are points analysis_recipe = SolarAccessGridBased(sun_vectors, hoys, [analysis_grids], timestep) else: print "missing sun vector data" return #HB surfaces #convert scene hb objects into rhino common geo_list = [] for id in hb_object_ids: if rs.IsBrep(id): geo_list += [rc.DocObjects.ObjRef(id).Brep()] elif rs.IsMesh(id): geo_list += [rc.DocObjects.ObjRef(id).Mesh()] else: continue #preapre paramters if len(geo_list) != 0 and geo_list[0] != None: names = None #not included yet in eto interface (could use scene object name) hb_objects = [] for index, geo in enumerate(geo_list): type = hb_object_types[index] radMat = hb_object_mats[index] isNameSetByUser = False if names: isNameSetByUser = True isTypeSetByUser = True if not type: isTypeSetByUser = False rad_prop = RadianceProperties( radMat) if radMat else RadianceProperties() ep_prop = None if radMat and radMat.__class__.__name__ == 'Plastic': hb_objects += HBSurface.from_geometry( names, geo, type, isNameSetByUser, isTypeSetByUser, rad_prop, ep_prop) elif radMat and radMat.__class__.__name__ == 'Glass': hb_objects += HBFenSurface.from_geometry( names, geo, isNameSetByUser, rad_prop, ep_prop) else: print "No valid HB surfaces selected" return # Run analysis rad_scene = None if not hb_objects or not analysis_recipe: print "Missing HB objects or analysis recipe" return try: for obj in hb_objects: assert hasattr(obj, 'isHBObject') except AssertionError: raise ValueError( "\n{} is not a valid Honeybee object.".format(obj)) assert hasattr(analysis_recipe, 'isAnalysisRecipe'), \ ValueError("\n{} is not a Honeybee recipe.".format(analysis_recipe)) legend_par = analysis_recipe.legend_parameters #write to file # Add Honeybee objects to the recipe analysis_recipe.hb_objects = hb_objects analysis_recipe.scene = rad_scene batch_file = analysis_recipe.write(folder, filename) #run if 'save file only' is not checked outputs = None if not save_file_only: if analysis_recipe.run(batch_file, False): try: outputs = analysis_recipe.results() except StopIteration: raise ValueError( 'Length of the results is smaller than the analysis grids ' 'point count [{}]. In case you have changed the analysis' ' Grid you must re-calculate daylight/view matrix!' .format(analysis_recipe.total_point_count)) if outputs: LadybugEto.displayAnalysis(grid_mesh, outputs, legend_par, filename) except Exception as e: print e
def add_nodes_elements_from_layers(structure, layers, line_type=None, mesh_type=None, acoustic=False, thermal=False): """ Adds node and element data from Rhino layers to Structure object. Parameters ---------- structure : obj Structure object to update. layers : list Layers to extract nodes and elements. line_type : str Element type for lines. mesh_type : str Element type for meshes. acoustic : bool Acoustic properties on or off. thermal : bool Thermal properties on or off. Returns ------- list Node keys that were added to the Structure. list Element keys that were added to the Structure. """ if isinstance(layers, str): layers = [layers] created_nodes = set() created_elements = set() for layer in layers: elset = set() for guid in rs.ObjectsByLayer(layer): if line_type and rs.IsCurve(guid): sp_xyz = rs.CurveStartPoint(guid) ep_xyz = rs.CurveEndPoint(guid) sp = structure.add_node(sp_xyz) ep = structure.add_node(ep_xyz) sp_ep = [sp, ep] created_nodes.add(sp) created_nodes.add(ep) ez = subtract_vectors(ep_xyz, sp_xyz) try: dic = json.loads(rs.ObjectName(guid).replace("'", '"')) ex = dic.get('ex', None) ey = dic.get('ey', None) if ex and not ey: ey = cross_vectors(ex, ez) except: ex = None ey = None axes = {'ex': ex, 'ey': ey, 'ez': ez} e = structure.add_element(nodes=sp_ep, type=line_type, acoustic=acoustic, thermal=thermal, axes=axes) if e is not None: created_elements.add(e) elset.add(e) elif mesh_type and rs.IsMesh(guid): vertices = rs.MeshVertices(guid) nodes = [structure.add_node(vertex) for vertex in vertices] created_nodes.update(nodes) if mesh_type in [ 'HexahedronElement', 'TetrahedronElement', 'SolidElement', 'PentahedronElement' ]: e = structure.add_element(nodes=nodes, type=mesh_type, acoustic=acoustic, thermal=thermal) if e is not None: created_elements.add(e) elset.add(e) else: try: dic = json.loads(rs.ObjectName(guid).replace("'", '"')) ex = dic.get('ex', None) ey = dic.get('ey', None) if ex and ey: ez = cross_vectors(ex, ey) else: ez = None except: ex = None ey = None ez = None axes = {'ex': ex, 'ey': ey, 'ez': ez} for face in rs.MeshFaceVertices(guid): nodes = [ structure.check_node_exists(vertices[i]) for i in face ] if nodes[-1] == nodes[-2]: del nodes[-1] e = structure.add_element(nodes=nodes, type=mesh_type, acoustic=acoustic, thermal=thermal, axes=axes) if e is not None: created_elements.add(e) elset.add(e) structure.add_set(name=layer, type='element', selection=list(elset)) return list(created_nodes), list(created_elements)
def bakeObject(_obj, _attrs, _layer): """ Takes in an obj and bakes to a Layer If the Object is a Mesh, will bake that using the Mesh's Vertex Colors. To set these, use the Grasshopper MeshColor component (ghc.MeshColours() ) before inputting here. If its a Curve input, will try and look for Attribute information in the _geomAttributes input. If its some other type of geometry, will just use a default attribute for printing. """ doc_object = rs.coercerhinoobject(_obj, True, True) geometry = doc_object.Geometry sc.doc = Rhino.RhinoDoc.ActiveDoc layerT = Rhino.RhinoDoc.ActiveDoc.Layers #layer table if rs.IsMesh(geometry): # Find the targer layer index parentLayerIndex = Rhino.DocObjects.Tables.LayerTable.FindByFullPath( layerT, _layer, True) # Create a hatch from the mesh guids = [] hatches, colors = mesh2Hatch(geometry) # Bake the Hatches into the Rhino Doc for count, hatch in enumerate(hatches): attr = Rhino.DocObjects.ObjectAttributes() attr.LayerIndex = parentLayerIndex attr.ColorSource = Rhino.DocObjects.ObjectColorSource.ColorFromObject attr.ObjectColor = colors[count] attr.DisplayOrder = -1 # 1 = Front, -1 = Back guids.append(Rhino.RhinoDoc.ActiveDoc.Objects.AddHatch( hatch, attr)) # Group the hatches so are manageable groupT = Rhino.RhinoDoc.ActiveDoc.Groups Rhino.DocObjects.Tables.GroupTable.Add(groupT, guids) sc.doc.Views.Redraw() elif geometry.GetType( ) == Rhino.Geometry.PolylineCurve or geometry.GetType( ) == Rhino.Geometry.Curve: # If its a curve, use the input User Determined Attributes # Check that the input is a good ObjectAttributes Object if type(_attrs) is Rhino.DocObjects.ObjectAttributes: attr = _attrs else: doc_object.Attributes rhino_geom = sc.doc.Objects.Add(geometry, attr) # Set the new Object's Layer if not rs.IsLayer(_layer): rs.AddLayer(_layer) rs.ObjectLayer(rhino_geom, _layer) else: # Just bake the regular Geometry with default attributes rhino_geom = sc.doc.Objects.Add(geometry, doc_object.Attributes) # Set the new Object's Layer if not rs.IsLayer(_layer): rs.AddLayer(_layer) rs.ObjectLayer(rhino_geom, _layer) sc.doc = ghdoc
def ProjectCurvesToTIN(): try: crvs = rs.GetObjects(message="Select curves to project", filter=4, group=True, preselect=False, select=False, objects=None, minimum_count=1, maximum_count=0, custom_filter=None) if not crvs: return obj = rs.GetObject("Select the TIN to project onto", 8 | 16 | 32) if not obj: return isMesh = rs.IsMesh(obj) zUpList = [] zDownList = [] rs.EnableRedraw(False) # Convert Mesh to Nurbs for ShootRay compatibility if isMesh == True: srf = rs.MeshToNurb(obj) if isMesh == False: srf = obj # Shoot ray from each grip point and move grips to reflection point for crv in crvs: rs.EnableObjectGrips(crv) grips = rs.ObjectGripLocations(crv) for grip in grips: zUp = rs.ShootRay(srf, grip, (0, 0, 1), 1) # if zUp != None: if zUp == None: zUpList.append(False) else: zUpList.append(zUp[1]) zDown = rs.ShootRay(srf, grip, (0, 0, -1), 1) # if zDown != None: if zDown == None: zDownList.append(False) else: zDownList.append(zDown[1]) rs.CopyObject(crv) # Copy Existing curve # Find the right list to iterate over and insert existing points for any falses if all(x is False for x in zUpList): falseindex = [i for i, val in enumerate(zDownList) if not val] for i in falseindex: # Replace False with existing grip location and closest Z value closestPt = rs.BrepClosestPoint(srf, grips[i]) zDownList[i] = (grips[i].X, grips[i].Y, closestPt[0].Z) rs.ObjectGripLocations(crv, zDownList) else: falseindex = [i for i, val in enumerate(zUpList) if not val] for i in falseindex: # Replace False with existing grip location and closest Z value closestPt = rs.BrepClosestPoint(srf, grips[i]) zUpList[i] = (grips[i].X, grips[i].Y, closestPt[0].Z) rs.ObjectGripLocations(crv, zUpList) del zDownList[:] del zUpList[:] rs.EnableObjectGrips(crv, False) if isMesh == True: rs.DeleteObject(srf) rs.EnableRedraw(True) except: rs.EnableObjectGrips(crv, False) rs.DeleteObject(crv) rs.EnableRedraw(True) print("Failed to project curves") return
def ScatterBlocks(): try: ################################################################################ # GET OBJECTS AND VARIABLE # ################################################################################ obj = rs.GetObject(message="Select surface to scatter on", filter=8 | 16 | 32, preselect=False, select=False, custom_filter=None, subobjects=False) if not obj: return blocks = rs.GetObjects(message="Select blocks to scatter", filter=4096, group=True, preselect=False, select=False, objects=None, minimum_count=1, maximum_count=0, custom_filter=None) if not blocks: return scatterNum = rs.GetInteger( message="Enter scatter amount", number=100, minimum=1, maximum=10000) if not scatterNum: return userScale = rs.GetReal( "enter scale multiplyer (0 for no scaling)", number=0, minimum=None, maximum=None) userRotation = rs.GetBoolean( "random rotation of blocks?", ("Rotation", "No", "Yes"), (True)) if not userRotation: return isMesh = rs.IsMesh(obj) ptBucket = 0 pointList = [] blockList = [] worldZVector = (rs.WorldXYPlane()).ZAxis rs.EnableRedraw(False) def MeshBrep(brep_id, params): brep = rs.coercebrep(brep_id) if brep: mesh = Rhino.Geometry.Mesh() mesh_parts = Rhino.Geometry.Mesh.CreateFromBrep(brep, params) for mesh_part in mesh_parts: mesh.Append(mesh_part) mesh.Compact() return mesh def TestMeshBrep(): mesh_params = Rhino.Geometry.MeshingParameters.Coarse mesh_brep = MeshBrep(obj, mesh_params) if mesh_brep: mesh = sc.doc.Objects.AddMesh(mesh_brep) return mesh def chunks(lst, n): # list split generator for i in xrange(0, len(lst), n): yield lst[i:i + n] if isMesh == False: mesh = TestMeshBrep() else: mesh = obj # Get and format vertex points in mesh, format from point3d object to float list meshVerts = rs.MeshFaces(mesh, face_type=False) totalArea = rs.MeshArea(mesh) meshFaceCount = rs.MeshFaceCount(mesh) PT01 = meshVerts[0::3] PT01S = [] for i in PT01: i = (i.X, i.Y, i.Z) PT01S.append(i) PT02 = meshVerts[1::3] PT02S = [] for i in PT02: i = (i.X, i.Y, i.Z) PT02S.append(i) PT03 = meshVerts[2::3] PT03S = [] for i in PT03: i = (i.X, i.Y, i.Z) PT03S.append(i) # format list together in order to loop through triangleList = zip(PT01S, PT02S, PT03S) ################################################################################ # POINT SCATTER LOOP # ################################################################################ # loop through the three vertexes forming individual triangles for i in triangleList: a = i[0] # triangle vert 1 b = i[1] # triangle vert 2 c = i[2] # triangle vert 3 # Find area of triangle dist01 = rs.Distance(a, b) dist02 = rs.Distance(a, c) dist03 = rs.Distance(b, c) # Herons formula to find area of triangle by sides s = (dist01 + dist02 + dist03) / 2 tArea = math.sqrt(s*(s-dist01)*(s-dist02)*(s-dist03)) # assign portion of points base on area of triangle, if assignment of points is lower then one, add that to the next assignment numPtsPerUnit = totalArea[1] / scatterNum ptAllocation = tArea / numPtsPerUnit ptBucket = ptBucket + ptAllocation if ptBucket < 1: continue else: pointShare = int(math.floor(ptBucket)) ptBucket = 0 # Vectors from origin to either corner of triangle ac = rs.VectorCreate(c, a) ab = rs.VectorCreate(b, a) originVector = rs.VectorCreate(a, (0, 0, 0)) # Generate random numbers between 0,1. Random scatter onto triangle for i in range(pointShare): r1 = random.random() r2 = random.random() if r1 + r2 < 1: p = r1 * ac + r2 * ab else: p = (1 - r1) * ac + (1 - r2) * ab points = rs.AddPoint(p) pointList.append(points) rs.MoveObjects(points, originVector) ################################################################################ # MOVE BLOCKS TO POINTS WITH ROTATION / SCALE # ################################################################################ # shuffle point list then split list by the number of blocks to scatter. Copy blocks to split lists random.shuffle(pointList) ptDivision = int(len(pointList) / len(blocks)) genList = chunks(pointList, ptDivision) blockIndex = 0 for pts in genList: # looping through split point list and blocks and copying blocks to scatter blockPt = rs.BlockInstanceInsertPoint(blocks[blockIndex]) for pt in pts: vector = rs.VectorCreate(pt, blockPt) newBlock = rs.CopyObject(blocks[blockIndex], vector) # create list of blocks for later modification blockList.append(newBlock) if blockIndex < (len(blocks) - 1): blockIndex += 1 # apply random scaling and rotation to blocks if userRotation[0] == True: for block in blockList: centerPt = rs.BlockInstanceInsertPoint(block) angle = random.randint(0, 360) rs.RotateObject(block, centerPt, angle, worldZVector) for block in blockList: centerPt = rs.BlockInstanceInsertPoint(block) scale = random.uniform((userScale/4), userScale) rs.ScaleObject(block, centerPt, (scale, scale, scale)) # If a mesh was created, delete it, general cleanup if isMesh == False: rs.DeleteObject(mesh) rs.DeleteObjects(pointList) rs.EnableRedraw(True) except: print("Failed to execute") rs.EnableRedraw(True) return
def FilamentCalculator(): """3D Printing filament length, weight, volume calculator.""" input_obj = rs.SelectedObjects() if not input_obj: input_obj = rs.GetObjects("Select objects") if not input_obj: return volume = 0.0 for o in input_obj: if rs.IsMesh(o): a, b, c = rs.MeshVolume(o) volume += b elif rs.IsObjectSolid(o): a, b = rs.SurfaceVolume(o) volume += a if volume == 0.0: return filaments = { "PLA": 1.24, "ABS": 1.05, "ASA": 1.07, "PETG": 1.27, "PETT": 1.45, "HIPS": 1.07, "TPU": 1.30, "PMMA": 1.18, "Nylon": 1.08, "Polycarbonate": 1.20, "Copperfill": 3.90 } filament = rs.GetString("Material:", "PLA", [a for a in filaments]) density = filaments[filament] volume = volume / rs.UnitScale(rs.UnitSystem(), 3)**3 weight = volume * filaments[filament] l1 = volume / (math.pi * (0.175 / 2)**2) / 100 l2 = volume / (math.pi * (0.285 / 2)**2) / 100 l3 = volume / (math.pi * (0.3 / 2)**2) / 100 volume = round(volume, 3) weight = round(weight, 3) l1 = round(l1, 2) l2 = round(l2, 2) l3 = round(l3, 2) message = """{f}: Density = {d} grams / cubic centimeter Volume = {v} cubic centimeters Weight ~ {w} grams 1.75 mm filament length ~ {l1} meters 2.85 mm filament length ~ {l2} meters 3.00 mm filament length ~ {l3} meters""" message = message.format(f=filament, d=density, v=volume, w=weight, l1=l1, l2=l2, l3=l3) rs.MessageBox(message, buttons=0, title="FilamentCalculator:") print(message)
def getSelectedMesh(self): selected = rs.SelectedObjects() for objId in selected: if rs.IsMesh(objId): return self.getGeomFromGUID(objId) return None