def rhino_volmesh_cell_subdivide_barycentric(volmesh, formdiagram=None): cell_colors = {} ckeys = volmesh.cell.keys() for index, ckey in enumerate(ckeys): color = (0, 0, 0) if len(ckeys) != 1: value = float(index) / (len(ckeys) - 1) color = i_to_rgb(value) cell_colors[ckey] = color volmesh.clear() volmesh.draw_edges() volmesh.draw_faces() volmesh.draw_cell_labels(colors=True) rs.EnableRedraw(True) # dynamic selector cell_inspector = VolmeshCellInspector(volmesh, color_dict=cell_colors) cell_inspector.enable() sel_ckeys = CellSelector.select_cells(volmesh) cell_inspector.disable() del cell_inspector volmesh.clear_cell_labels() for ckey in sel_ckeys: volmesh_cell_subdivide_barycentric(volmesh, ckey) volmesh.clear() volmesh.draw() return volmesh
def get_faces_lable(): is_not_loaded = list( datastructure.faces_where({'_is_loaded': False})) faces_to_draw = list( set(list(datastructure.faces())) - set(is_not_loaded)) faces_selected = keys faces_unselected = list(set(faces_to_draw) - set(faces_selected)) # noqa E501 labels = [] values = [ datastructure.face_attribute(face, attr) for face in faces_to_draw ] v_max = max(values) v_min = min(values) v_range = v_max - v_min or v_max or 1 for face in faces_to_draw: value = datastructure.face_attribute(face, attr) if face in faces_selected: color = [0, 0, 0] else: color = i_to_rgb(value / v_range) pos = datastructure.face_centroid(face) value = '{:.3g}'.format(value) labels.append({'pos': pos, 'text': value, 'color': color}) return labels, faces_to_draw
def volmesh3gs_select_cell(volmesh): cell_colors = {} ckeys = volmesh.cell.keys() for index, ckey in enumerate(ckeys): value = 0 if len(ckeys) > 1: value = float(index) / (len(ckeys) - 1) color = i_to_rgb(value) cell_colors[ckey] = color volmesh.draw_cell_labels(color_dict=cell_colors) rs.EnableRedraw(True) # dynamic selector cell_inspector = VolmeshCellInspector(volmesh, color_dict=cell_colors) cell_inspector.enable() ckey = CellSelector.select_cell(volmesh) cell_inspector.disable() del cell_inspector volmesh.clear_cell_labels() return ckey
def DrawForeground(self, e): p1 = self.mouse.p1 p2 = self.mouse.p2 v12 = subtract_vectors(p2, p1) l12 = length_vector(v12) # force diagram for ckey in self.volmesh.cell: p0 = self.volmesh.cell_center(ckey) dual_p0 = self.network.vertex_coordinates(ckey) v01 = subtract_vectors(p1, p0) v02 = subtract_vectors(p2, p0) l = length_vector(cross_vectors(v01, v02)) if l12 == 0.0 or (l / l12) < self.tol: hf_colors = {} nbr_vkeys = self.network.vertex_neighbours(ckey) for index, nbr_vkey in enumerate(nbr_vkeys): value = float(index) / (len(nbr_vkeys) - 1) print('boo', value) color = i_to_rgb(value) color = System.Drawing.Color.FromArgb(*color) nbr_xyz = self.network.vertex_coordinates(nbr_vkey) e.Display.DrawLine(Point3d(*dual_p0), Point3d(*nbr_xyz), color, 4) hfkey = self.volmesh.cell_pair_halffaces(ckey, nbr_vkey)[0] hf_colors[hfkey] = color for hfkey in self.volmesh.cell_halffaces(ckey): vkeys = self.volmesh.halfface_vertices(hfkey) face_coordinates = [ self.volmesh.vertex_coordinates(vkey) for vkey in vkeys ] face_coordinates.append(face_coordinates[0]) polygon_xyz = [Point3d(*xyz) for xyz in face_coordinates] e.Display.DrawDot(Point3d(*p0), str(ckey), self.dotcolor, self.textcolor) e.Display.DrawPolyline(polygon_xyz, self.edgecolor, 2) e.Display.DrawDot(Point3d(*dual_p0), str(ckey), self.dotcolor, self.textcolor) if hfkey in hf_colors: hf_color = hf_colors[hfkey] e.Display.DrawPolygon(polygon_xyz, hf_color, filled=True) break
def callback(k, args): for index in range(len(vertices_1)): if index in fixed: vertices_1[index][2] = 0 if k % 5 == 0: dev = flatness(vertices_1, faces, 0.02) conduit.colors = [ FromArgb(*i_to_rgb(dev[i])) for i in range(len(faces)) ] conduit.redraw()
def callback(k, args): print(k) if k % 100 == 0: dev = mesh_flatness(mesh, maxdev=0.02) plotter.update_vertices(radius=radius) plotter.update_faces( facecolor={fkey: i_to_rgb(dev[fkey]) for fkey in mesh.faces()}) plotter.update_edges() plotter.update()
def plot_diffuse_loads(vibro, real=True): mesh = vibro.mesh for fk in vibro.frequencies: freq = 'loads' + str(vibro.frequencies[fk]) + 'Hz' loads = vibro.diffuse_field_loads[fk] if real: loads = [l.real for l in loads] else: loads = [l.imag for l in loads] maxl = max(loads) minl = min(loads) sloads = [(l - minl) / (maxl - minl) for l in loads] color = {i: i_to_rgb(l) for i, l in enumerate(sloads)} mesh_draw(mesh, facecolor=color, layer=freq, clear_layer=True)
def callback(k, plotter, clusters, filepath): num = len(list(clusters.keys())) facedict = {} for idx, cluster in clusters.items(): color = [i / 255 for i in i_to_rgb(idx / num)] for fkey in cluster.faces_keys: facedict[fkey] = color facecolors = sorted(facedict.items(), key=lambda x: x[0]) facecolors = [x[1] for x in facecolors] plotter.facecollection.set_facecolors(facecolors) # plotter.save(THERE + '{}_{}.png'.format(time(), k)) plotter.update(pause=0.5)
def draw_interface(vertices, faces, maxdev): # don't refresh viewport rs.EnableRedraw(False) # compute level of flatness flat_vals = flatness(vertices, faces, maxdev) srfs = [] for i, face in enumerate(faces): # vertex coordinates for face pts = [vertices[key] for key in face] # create Rhino surface srfs.append(rs.AddSrfPt(pts)) # color surface based on flatness rgb = i_to_rgb(flat_vals[i]) rs.ObjectColor(srfs[-1], rgb) rs.AddObjectsToGroup(srfs, rs.AddGroup()) # refresh viewport rs.EnableRedraw(True)
def plot_colored_vectors(centers, cluster_labels, angles, name, base_vector=[1, 0, 0]): max_angle = max(list(angles.values())) # dict fkey: angle centers = sort(centers.flatten()) # k-centroids scales = arange(1, centers.size + 1) * 3 # 3 is a factor scales = power(scales, 2) # squared factors for idx, center in enumerate(centers): cangles = { fkey: a for fkey, a in angles.items() if cluster_labels[fkey] == center } vectors = vectors_from_angles(cangles, base_vector) # create vectors X = array(list(vectors.values())) x = X[:, 0] y = X[:, 1] kcolor = array([[i / 255.0 for i in i_to_rgb(center / max_angle)]]) rcenter = round(center, 2) rdegcenter = round(degrees(center), 2) msg = "{} rad / {} deg".format(rcenter, rdegcenter) plt.scatter(x, y, c=kcolor, alpha=0.3, label=msg, s=scales[idx]) kvector = vector_from_angle(center, base_vector) plt.scatter(kvector[0], kvector[1], marker="x", color="black", s=200) plt.axes() plt.grid(b=None, which='major', axis='both', linestyle='--') plt.xlabel("x") plt.ylabel("y") plt.title("{}".format(name)) plt.legend() plt.show()
def get_edges_lable(): is_not_edge = list(datastructure.edges_where({'_is_edge': False})) edges_to_draw = list( set(list(datastructure.edges())) - set(is_not_edge)) edges_selected = list(set(keys) & set(edges_to_draw)) edges_unselected = list(set(edges_to_draw) - set(edges_selected)) # noqa E501 labels = [] values = [ datastructure.edge_attribute(edge, attr) for edge in edges_to_draw ] v_max = max(values) v_min = min(values) v_range = v_max - v_min or v_max or 1 for edge in edges_to_draw: value = datastructure.edge_attribute(edge, attr) if edge in edges_selected: color = [0, 0, 0] else: color = i_to_rgb(value / v_range) # project to xy plane if datastructure.attributes['name'] == 'form': pos = [ datastructure.edge_midpoint(*edge)[0], datastructure.edge_midpoint(*edge)[1], 0 ] else: pos = datastructure.edge_midpoint(*edge) value = '{:.3g}'.format(value) labels.append({'pos': pos, 'text': value, 'color': color}) return labels, edges_to_draw
def get_vertices_lable(): vertices_to_draw = list(datastructure.vertices()) vertices_selected = keys vertices_unselected = list( set(vertices_to_draw) - set(vertices_selected)) # noqa E501 labels = [] values = [ datastructure.vertex_attribute(vertex, attr) for vertex in vertices_to_draw ] v_max = max(values) v_min = min(values) v_range = v_max - v_min or v_max or 1 for vertex in vertices_to_draw: value = datastructure.vertex_attribute(vertex, attr) if vertex in vertices_selected: color = [0, 0, 0] else: color = i_to_rgb(value / v_range) # project to xy plane if datastructure.attributes['name'] == 'form': pos = [ datastructure.vertex_coordinates(vertex)[0], datastructure.vertex_coordinates(vertex)[1], 0 ] else: pos = datastructure.vertex_coordinates(vertex) value = '{:.3g}'.format(value) labels.append({'pos': pos, 'text': value, 'color': color}) return labels, vertices_to_draw
attr['x'] = xyz[key][0] attr['y'] = xyz[key][1] attr['z'] = xyz[key][2] # plot the starting configuration plotter.draw_vertices(facecolor={ key: '#000000' for key in network.vertices_where({'is_fixed': True}) }) plotter.draw_edges() plotter.update(pause=1.0) # run the DR network_dr(network, callback=callback) # plot the final configuration fmax = max(network.get_edges_attribute('f')) plotter.draw_vertices(facecolor={ key: '#000000' for key in network.vertices_where({'is_fixed': True}) }) plotter.draw_edges(color={(u, v): i_to_rgb(attr['f'] / fmax) for u, v, attr in network.edges(True)}, width={(u, v): 10 * attr['f'] / fmax for u, v, attr in network.edges(True)}) plotter.show()
try: ad = network.get_edge_attribute((fkey, nbr), 'angle_diff') if ad: continue except: network.add_edge(fkey, nbr, attr_dict={'angle_diff': angle_diff}) # # ========================================================================== # # color up # # ========================================================================== anglemax = max(network.get_edges_attribute('angle_diff')) print('angle diff max', anglemax) colors = {} for u, v, attr in network.edges(True): angle_diff = attr['angle_diff'] color = i_to_rgb(angle_diff / anglemax) colors[(u, v)] = color # # ========================================================================== # # Set up Plotter # # ========================================================================== plotter = NetworkPlotter(network, figsize=(12, 9)) # plotter.draw_faces(facecolor=colors) plotter.draw_vertices(radius=0.01) plotter.draw_edges(color=colors) plotter.show()
with conduit.enabled(): planarize_faces(vertices_1, faces, kmax=500, callback=callback) # compute the *flatness* dev0 = flatness(vertices_0, faces, 0.02) dev1 = flatness(vertices_1, faces, 0.02) # draw the original compas_rhino.mesh_draw_faces(mesh, layer='mesh_start', clear_layer=True, color={ fkey: i_to_rgb(dev0[index]) for index, fkey in enumerate(mesh.faces()) }) # draw the result for key, attr in mesh.vertices(True): index = key_index[key] attr['x'] = vertices_1[index][0] attr['y'] = vertices_1[index][1] attr['z'] = vertices_1[index][2] color = { fkey: i_to_rgb(dev1[index]) for index, fkey in enumerate(mesh.faces()) }
curvature = trimesh_gaussian_curvature(mesh) plotter = MeshPlotter(mesh, figsize=(12, 8), tight=True) # lines = [] # for index, key in enumerate(mesh.vertices()): # vector = d[index] # start = xyz[index] # end = subtract_vectors(start, vector) # lines.append({ # 'start' : end, # 'end' : start, # 'arrow' : 'start', # 'color' : '#ff0000' # }) c_min = min(curvature) c_max = max(curvature) c_spn = c_max - c_min plotter.draw_vertices(radius=0.1, facecolor={ key: i_to_rgb((curvature[key] - c_min) / c_spn) for key in mesh.vertices() }) plotter.draw_faces() # plotter.draw_arrows(lines) plotter.show()
key_index = mesh.key_index() V = mesh.vertices_attributes('xyz') F = [[key_index[key] for key in mesh.face_vertices(fkey)] for fkey in mesh.faces()] S = mesh.vertices_attribute('z') N = 50 vertices, levels = igl.trimesh_isolines(V, F, S, N) # ============================================================================== # Visualisation # ============================================================================== smin = min(S) smax = max(S) lines = [] for scalar, edges in levels: for i, j in edges: lines.append({ 'start': vertices[i], 'end': vertices[j], 'color': i_to_rgb((scalar - smin) / (smax - smin)) }) plotter = MeshPlotter(mesh, figsize=(8, 5)) plotter.draw_faces() plotter.draw_lines(lines) plotter.show()
attr['x'] = xyz[index, 0] attr['y'] = xyz[index, 1] attr['z'] = xyz[index, 2] xyz, q, f, l, r = dr_numpy(vertices, edges, fixed, loads, qpre, fpre, lpre, linit, E, radius, kmax=100, callback=callback) for index, (u, v, attr) in enumerate(mesh.edges(True)): attr['f'] = f[index, 0] attr['l'] = l[index, 0] fmax = max(mesh.get_edges_attribute('f')) plotter.clear_vertices() plotter.clear_edges() plotter.draw_vertices( facecolor={key: '#000000' for key in mesh.vertices_where({'is_fixed': True})} ) plotter.draw_edges( text={(u, v): '{:.0f}'.format(attr['f']) for u, v, attr in mesh.edges(True)}, color={(u, v): i_to_rgb(attr['f'] / fmax) for u, v, attr in mesh.edges(True)}, width={(u, v): 10 * attr['f'] / fmax for u, v, attr in mesh.edges(True)} ) plotter.update(pause=1.0) plotter.show()
line = Line(* box.diagonal) # ============================================================================== # Slices # ============================================================================== N = 9 slices = [] a = line.start for i in range(1, N + 1): b = a + line.direction * i * 0.1 * line.length plane = Plane(b, line.direction) mesh, B = mesh.slice_plane(plane) slices.append(B) slices.append(mesh) # ============================================================================== # Exploded viz # ============================================================================== viewer = App() for i, mesh in enumerate(slices): T = Translation.from_vector(line.direction * i * 0.05 * line.length) viewer.add(mesh.transformed(T), facecolor=i_to_rgb(i / N, normalize=True)) viewer.run()
print('max angle', min(angles.values())) print('min angle', max(angles.values())) for idx, angle in angles.items(): if angle <= 90.0: continue angles[idx] = 180.0 - angle print('max angle', min(angles.values())) print('min angle', max(angles.values())) anglemax = max(angles.values()) colors = {} for idx, angle in angles.items(): color = i_to_rgb(angle / anglemax) colors[idx] = color vectors = {} for fkey, angle in angles.items(): y = 1.0 / math.tan(math.radians(angle)) x_vec = [1.0, 0.0, 0.0] y_vec = [0.0, y, 0.0] vec = normalize_vector(add_vectors(x_vec, y_vec)) vectors[fkey] = vec # ========================================================================== # Create Face Adjacency Network - keys from 0 to N! # ========================================================================== n = mesh.number_of_faces()
def OnDynamicDraw(sender, e): cp = e.CurrentPoint plane = (cp, f_normal) new_pt_list = [] for u in f_vkeys: v = edges[u] u_xyz = cell.vertex_coordinates(u) v_xyz = cell.vertex_coordinates(v) line = (u_xyz, v_xyz) it = intersection_line_plane(line, plane) xyz_dict[u] = it new_pt_list.append(it) e.Display.DrawDottedLine(Point3d(*u_xyz), Point3d(*it), black) for vkey in cell.vertex: xyz = cell.vertex_coordinates(vkey) e.Display.DrawPoint(Point3d(*xyz), 0, 5, black) # old normal and area -------------------------------------------------- e.Display.DrawDot(Point3d(*f_center), str(round(f_area, 3)), gray, white) # draw original face --------------------------------------------------- for i in range(-1, len(f_vkeys) - 1): vkey1 = f_vkeys[i] vkey2 = f_vkeys[i + 1] sp = Point3d(*cell.vertex_coordinates(vkey1)) np = Point3d(*cell.vertex_coordinates(vkey2)) e.Display.DrawDottedLine(sp, np, black) # get current face info ------------------------------------------------ areas = {} normals = {} for fkey in cell.faces(): face_coordinates = [ xyz_dict[vkey] for vkey in cell.face_vertices(fkey) ] areas[fkey] = polygon_area_oriented(face_coordinates) normals[fkey] = polygon_normal_oriented(face_coordinates) # draw new face areas / vectors ---------------------------------------- for fkey in cell.faces(): area = areas[fkey] normal = normals[fkey] value = area / max(areas.values()) color = i_to_rgb(value) color = FromArgb(*color) # draw vectors ----------------------------------------------------- scale = 0.25 center = datastructure_centroid(cell) sp = Point3d(*center) vector = scale_vector(normal, area * scale) ep = Point3d(*add_vectors(center, vector)) e.Display.DrawArrow(Line(sp, ep), color, 20, 0) # draw face -------------------------------------------------------- face_coordinates = [ xyz_dict[vkey] for vkey in cell.face_vertices(fkey) ] face_coordinates.append(face_coordinates[0]) polygon_xyz = [Point3d(*xyz) for xyz in face_coordinates] e.Display.DrawPolyline(polygon_xyz, black, 2) if fkey == face: e.Display.DrawPolyline(polygon_xyz, black, 4) e.Display.DrawPolygon(polygon_xyz, color, filled=True) # display force magnitudes ----------------------------------------- vector = add_vectors(vector, scale_vector(normalize_vector(normal), 0.75)) xyz = add_vectors(center, vector) if fkey == face: color = black e.Display.DrawDot(Point3d(*xyz), str(round(area, 2)), color, white)
# make a mesh from a JSON file mesh1 = Mesh.from_json(FILE) # extract the vertices and faces of the mesh vertices, faces = mesh1.to_vertices_and_faces() # compute the vertices of the planarized mesh planar = planarization.planarize(vertices, faces) # make a new mesh from the new vertex coordinates mesh2 = Mesh.from_vertices_and_faces(planar, faces) # compute the deviation from "flat" per face of both meshes dev1 = mesh_flatness(mesh1, maxdev=0.02) dev2 = mesh_flatness(mesh2, maxdev=0.02) # compute the color of each face based on its flatness facecolors = {} for fkey in mesh2.faces(): r, g, b = i_to_rgb(dev2[fkey]) facecolors[fkey] = [r / 255.0, g / 255.0, b / 255.0] # clean the scene for o in bpy.data.objects: o.select_set(True) bpy.ops.object.delete() # visualize the result artist = MeshArtist(mesh2) artist.draw_faces(colors=facecolors)
def draw(self): """Draw the force diagram in Rhino using the current settings.""" layer = self.settings["layer"] self.artist.layer = layer self.artist.clear_layer() group_vertices = "{}::vertices".format(layer) group_edges = "{}::edges".format(layer) if not compas_rhino.rs.IsGroup(group_vertices): compas_rhino.rs.AddGroup(group_vertices) if not compas_rhino.rs.IsGroup(group_edges): compas_rhino.rs.AddGroup(group_edges) # vertices guids_vertices = list(self.guid_vertex.keys()) delete_objects(guids_vertices, purge=True) keys = list(self.datastructure.vertices()) color = {key: self.settings["color.vertices"] for key in keys} guids = self.artist.draw_vertices(keys, color) self.guid_vertex = zip(guids, keys) compas_rhino.rs.AddObjectsToGroup(guids, group_vertices) if self.settings["show.vertices"]: compas_rhino.rs.ShowGroup(group_vertices) else: compas_rhino.rs.HideGroup(group_vertices) # edges guids_edges = list(self.guid_edge.keys()) delete_objects(guids_edges, purge=True) keys = list(self.datastructure.edges()) color = {key: self.settings['color.edges'] for key in keys} # color analysis if self.scene.settings['RV2']['show.forces']: lengths = [self.datastructure.edge_length(*key) for key in keys] lmin = min(lengths) lmax = max(lengths) for key, length in zip(keys, lengths): if lmin != lmax: color[key] = i_to_rgb((length - lmin) / (lmax - lmin)) guids = self.artist.draw_edges(keys, color) self.guid_edge = zip(guids, keys) compas_rhino.rs.AddObjectsToGroup(guids, group_edges) if self.settings["show.edges"]: compas_rhino.rs.ShowGroup(group_edges) else: compas_rhino.rs.HideGroup(group_edges) # angles if self.scene.settings['RV2']['show.angles']: tol = self.scene.settings['RV2']['tol.angles'] keys = list(self.datastructure.edges()) angles = self.datastructure.edges_attribute('_a', keys=keys) amin = min(angles) amax = max(angles) if (amax - amin)**2 > 0.001**2: text = {} color = {} for key, angle in zip(keys, angles): if angle > tol: text[key] = "{:.0f}".format(angle) color[key] = i_to_rgb((angle - amin) / (amax - amin)) guids = self.artist.draw_edgelabels(text, color) self.guid_edgelabel = zip(guids, keys) else: guids_edgelabels = list(self.guid_edgelabel.keys()) delete_objects(guids_edgelabels, purge=True) del self._guid_edgelabel self._guid_edgelabel = {}
# ============================================================================== # Input # ============================================================================== TOL = 0.02 MAXDEV = 0.005 KMAX = 500 mesh = Mesh.from_off(igl.get('tubemesh.off')) # ============================================================================== # Planarize # ============================================================================== V, F = mesh.to_vertices_and_faces() V2 = igl.quadmesh_planarize((V, F), KMAX, MAXDEV) # ============================================================================== # Visualize # ============================================================================== mesh = Mesh.from_vertices_and_faces(V2, F) dev = mesh_flatness(mesh, maxdev=TOL) plotter = MeshPlotter(mesh, figsize=(8, 5)) plotter.draw_faces( facecolor={fkey: i_to_rgb(dev[fkey]) for fkey in mesh.faces()}) plotter.show()
def draw(self): """Draw the objects representing the force diagram. """ layer = self.settings["layer"] self.artist.layer = layer self.artist.clear_layer() self.clear() if not self.visible: return self.artist.vertex_xyz = self.vertex_xyz # ====================================================================== # Groups # ------ # Create groups for vertices and edges. # These groups will be turned on/off based on the visibility settings of the diagram # ====================================================================== group_vertices = "{}::vertices".format(layer) group_edges = "{}::edges".format(layer) if not compas_rhino.rs.IsGroup(group_vertices): compas_rhino.rs.AddGroup(group_vertices) if not compas_rhino.rs.IsGroup(group_edges): compas_rhino.rs.AddGroup(group_edges) # ====================================================================== # Vertices # -------- # Draw the vertices and add them to the vertex group. # ====================================================================== vertices = list(self.mesh.vertices()) color = {vertex: self.settings["color.vertices"] for vertex in vertices} guids = self.artist.draw_vertices(vertices, color) self.guid_vertex = zip(guids, vertices) compas_rhino.rs.AddObjectsToGroup(guids, group_vertices) if self.settings["show.vertices"]: compas_rhino.rs.ShowGroup(group_vertices) else: compas_rhino.rs.HideGroup(group_vertices) # ====================================================================== # Edges # -------- # Draw the edges and add them to the edge group. # ====================================================================== edges = list(self.mesh.edges()) color = {edge: self.settings['color.edges'] for edge in edges} # color analysis if self.scene and self.scene.settings['RV2']['show.forces']: lengths = [self.mesh.edge_length(*edge) for edge in edges] lmin = min(lengths) lmax = max(lengths) for edge, length in zip(edges, lengths): if lmin != lmax: color[edge] = i_to_rgb((length - lmin) / (lmax - lmin)) guids = self.artist.draw_edges(edges, color) self.guid_edge = zip(guids, edges) compas_rhino.rs.AddObjectsToGroup(guids, group_edges) if self.settings["show.edges"]: compas_rhino.rs.ShowGroup(group_edges) else: compas_rhino.rs.HideGroup(group_edges) # ====================================================================== # Labels # ------ # Add labels for the angle deviations. # ====================================================================== if self.scene and self.scene.settings['RV2']['show.angles']: tol = self.scene.settings['RV2']['tol.angles'] edges = list(self.mesh.edges()) angles = self.mesh.edges_attribute('_a', keys=edges) amin = min(angles) amax = max(angles) if (amax - amin)**2 > 0.001**2: text = {} color = {} for edge, angle in zip(edges, angles): if angle > tol: text[edge] = "{:.0f}".format(angle) color[edge] = i_to_rgb((angle - amin) / (amax - amin)) guids = self.artist.draw_edgelabels(text, color) self.guid_edgelabel = zip(guids, edges)
spline1 = BSplineCurve.from_points(points1) points2 = [] points2.append(Point(-4, 0, 2)) points2.append(Point(-2, 2, 0)) points2.append(Point(2, 3, -1)) points2.append(Point(3, 7, -2)) points2.append(Point(4, 9, -1)) spline2 = BSplineCurve.from_points(points2) surface = BSplineSurface.from_fill(spline1, spline2) points = surface.xyz(nu=30, nv=20) n = len(points) colors = [i_to_rgb(i / n, normalize=True) for i in range(n)] # ============================================================================== # Viz # ============================================================================== mesh = surface.to_vizmesh() boundary = Polyline( mesh.vertices_attributes('xyz', keys=mesh.vertices_on_boundary())) view = App() view.add(mesh) view.add(boundary, linewidth=2) view.add(Collection(points), colors=colors, size=10) view.run()
import os from compas.datastructures import Network from compas.utilities import i_to_rgb from compas_rhino.artists import NetworkArtist HERE = os.path.dirname(__file__) FILE = os.path.join(HERE, 'clusters.json') network = Network.from_json(FILE) artist = NetworkArtist(network, layer="ITA20::Network") artist.clear_layer() nodecolor = { node: i_to_rgb(network.node_attribute(node, 'cluster') / 9) for node in network.nodes() } edgecolor = { edge: i_to_rgb(network.node_attribute(edge[0], 'cluster') / 9) for edge in network.edges() } artist.draw_nodes(color=nodecolor) artist.draw_edges(color=edgecolor)
attr['y'] = xyz[key][1] attr['z'] = xyz[key][2] for index, (u, v, attr) in enumerate(network.edges(True)): attr['f'] = f[index] attr['l'] = l[index] # visualize the final geometry # color the edges according to the size of the forces # set the width of the edges proportional to the internal forces fmax = max(network.get_edges_attribute('f')) plotter.clear_vertices() plotter.clear_edges() plotter.draw_vertices(facecolor={ key: '#000000' for key in network.vertices_where({'is_fixed': True}) }) plotter.draw_edges(text={(u, v): '{:.0f}'.format(attr['f']) for u, v, attr in network.edges(True)}, color={(u, v): i_to_rgb(attr['f'] / fmax) for u, v, attr in network.edges(True)}, width={(u, v): 10 * attr['f'] / fmax for u, v, attr in network.edges(True)}) plotter.update(pause=1.0) plotter.show()
def draw(self): """Draw the objects representing the thrust diagram. """ layer = self.settings['layer'] self.artist.layer = layer self.artist.clear_layer() self.clear() if not self.visible: return self.artist.vertex_xyz = self.vertex_xyz # ====================================================================== # Groups # ------ # Create groups for vertices, edges, and faces. # These groups will be turned on/off based on the visibility settings of the diagram. # Separate groups are created for free and anchored vertices. # ====================================================================== group_free = "{}::vertices_free".format(layer) group_anchor = "{}::vertices_anchor".format(layer) group_edges = "{}::edges".format(layer) group_faces = "{}::faces".format(layer) if not compas_rhino.rs.IsGroup(group_free): compas_rhino.rs.AddGroup(group_free) if not compas_rhino.rs.IsGroup(group_anchor): compas_rhino.rs.AddGroup(group_anchor) if not compas_rhino.rs.IsGroup(group_edges): compas_rhino.rs.AddGroup(group_edges) if not compas_rhino.rs.IsGroup(group_faces): compas_rhino.rs.AddGroup(group_faces) # ====================================================================== # Vertices # -------- # Draw the vertices and add them to the vertex group. # Free vertices and anchored vertices are drawn separately. # ====================================================================== free = list(self.mesh.vertices_where({'is_anchor': False})) anchors = list(self.mesh.vertices_where({'is_anchor': True})) color_free = self.settings['color.vertices'] if self.settings['_is.valid'] else self.settings['color.invalid'] color_anchor = self.settings['color.vertices:is_anchor'] color = {vertex: color_free for vertex in free} color.update({vertex: color_anchor for vertex in anchors}) guids_free = self.artist.draw_vertices(free, color) guids_anchor = self.artist.draw_vertices(anchors, color) self.guid_free = zip(guids_free, free) self.guid_anchor = zip(guids_anchor, anchors) compas_rhino.rs.AddObjectsToGroup(guids_free, group_free) compas_rhino.rs.AddObjectsToGroup(guids_anchor, group_anchor) if self.settings['show.vertices']: compas_rhino.rs.HideGroup(group_free) compas_rhino.rs.ShowGroup(group_anchor) else: compas_rhino.rs.HideGroup(group_free) compas_rhino.rs.HideGroup(group_anchor) # ====================================================================== # Edges # ----- # Draw the edges and add them to the edge group. # ====================================================================== edges = list(self.mesh.edges_where({'_is_edge': True})) color = {edge: self.settings['color.edges'] if self.settings['_is.valid'] else self.settings['color.invalid'] for edge in edges} # color analysis if self.scene and self.scene.settings['RV2']['show.forces']: if self.mesh.dual: _edges = list(self.mesh.dual.edges()) lengths = [self.mesh.dual.edge_length(*edge) for edge in _edges] edges = [self.mesh.dual.primal_edge(edge) for edge in _edges] lmin = min(lengths) lmax = max(lengths) for edge, length in zip(edges, lengths): if lmin != lmax: color[edge] = i_to_rgb((length - lmin) / (lmax - lmin)) guids = self.artist.draw_edges(edges, color) self.guid_edge = zip(guids, edges) compas_rhino.rs.AddObjectsToGroup(guids, group_edges) if self.settings['show.edges']: compas_rhino.rs.ShowGroup(group_edges) else: compas_rhino.rs.HideGroup(group_edges) # ====================================================================== # Faces # ----- # Draw the faces and add them to the face group. # ====================================================================== faces = list(self.mesh.faces_where({'_is_loaded': True})) color = {face: self.settings['color.faces'] if self.settings['_is.valid'] else self.settings['color.invalid'] for face in faces} guids = self.artist.draw_faces(faces, color) self.guid_face = zip(guids, faces) compas_rhino.rs.AddObjectsToGroup(guids, group_faces) if self.settings.get('show.faces', True): compas_rhino.rs.ShowGroup(group_faces) else: compas_rhino.rs.HideGroup(group_faces) # ====================================================================== # Overlays # -------- # Color overlays for various display modes. # ====================================================================== if self.settings['_is.valid'] and self.settings['show.selfweight']: tol = self.settings['tol.selfweight'] vertices = list(self.mesh.vertices()) color = self.settings['color.selfweight'] scale = self.settings['scale.selfweight'] guids = self.artist.draw_selfweight(vertices, color, scale, tol) self.guid_selfweight = zip(guids, vertices) if self.settings['_is.valid'] and self.settings['show.loads']: tol = self.settings['tol.externalforces'] vertices = list(self.mesh.vertices()) color = self.settings['color.loads'] scale = self.settings['scale.externalforces'] guids = self.artist.draw_loads(vertices, color, scale, tol) self.guid_load = zip(guids, vertices) if self.settings['_is.valid'] and self.settings['show.residuals']: tol = self.settings['tol.residuals'] vertices = list(self.mesh.vertices_where({'is_anchor': False})) color = self.settings['color.residuals'] scale = self.settings['scale.residuals'] guids = self.artist.draw_residuals(vertices, color, scale, tol) self.guid_residual = zip(guids, vertices) if self.settings['_is.valid'] and self.settings['show.reactions']: tol = self.settings['tol.externalforces'] anchors = list(self.mesh.vertices_where({'is_anchor': True})) color = self.settings['color.reactions'] scale = self.settings['scale.externalforces'] guids = self.artist.draw_reactions(anchors, color, scale, tol) self.guid_reaction = zip(guids, anchors) if self.settings['_is.valid'] and self.settings['show.pipes']: tol = self.settings['tol.pipes'] edges = list(self.mesh.edges_where({'_is_edge': True})) color = {edge: self.settings['color.pipes'] for edge in edges} # color analysis if self.scene and self.scene.settings['RV2']['show.forces']: if self.mesh.dual: _edges = list(self.mesh.dual.edges()) lengths = [self.mesh.dual.edge_length(*edge) for edge in _edges] edges = [self.mesh.dual.primal_edge(edge) for edge in _edges] lmin = min(lengths) lmax = max(lengths) for edge, length in zip(edges, lengths): if lmin != lmax: color[edge] = i_to_rgb((length - lmin) / (lmax - lmin)) scale = self.settings['scale.pipes'] guids = self.artist.draw_pipes(edges, color, scale, tol) self.guid_pipe = zip(guids, edges)
top = [] for point, normal in zip(bottom, normals): x = point[0] + 0.1 * normal[0] y = point[1] + 0.1 * normal[1] z = point[2] + 0.1 * normal[2] top.append([x, y, z]) # vertices and faces of the block vertices = bottom[::-1] + top faces = [[0, 1, 2, 3], [4, 5, 6, 7], [4, 3, 2, 5], [5, 2, 1, 6], [6, 1, 0, 7], [7, 0, 3, 4]] block = Mesh.from_vertices_and_faces(vertices, faces) block.name = "Block.{}".format(fkey) blocks.append(block) # ============================================================================== # Visualize the blocks # ============================================================================== artist = MeshArtist(None, layer="Blocks") artist.clear_layer() b = len(blocks) for i, block in enumerate(blocks): artist.mesh = block artist.draw_mesh(color=i_to_rgb(i / b)) artist.redraw()