def main(): parser = argparse.ArgumentParser(description='Generate gears.') parser.add_argument("input", help="JSON filename to read") args = parser.parse_args() data = json.load(open(args.input)) pieces = data["pieces"] out = sys.stdout x_multiplier = 1.0 cz_vertical_offset = 5 * DPI * 0 svg.header(out, WIDTH * x_multiplier, HEIGHT * 7) # Make cuts. for piece_index, piece in enumerate(data["pieces"]): cx = piece["cx"] * x_multiplier cy = piece["cy"] + piece["cz"] * cz_vertical_offset color = piece["color"] # Always use black for cut, it makes it easier to see in AI. color = "black" name = "%s_%d" % (piece["type"], piece_index) svg.start_group(out, name, cx, cy) p = piece["points"] svg.start_group(out, name + "_body") svg.polyline(out, p, color) svg.end_group(out) if "hole_radius" in piece: svg.start_group(out, name + "_hole") svg.circle(out, 0, 0, piece["hole_radius"], color) svg.end_group(out) if "bind" in piece: bind = piece["bind"] bind_radius = bind["hole_radius"] svg.start_group(out, name + "_bind") for center in bind["centers"]: svg.circle(out, center[0], center[1], bind_radius, color) svg.end_group(out) if "holes" in piece: # Also cut holes from all the axles. svg.start_group(out, name + "_holes") for hole in piece["holes"]: svg.circle(out, hole["cx"], hole["cy"], hole["r"], color) svg.end_group(out) svg.end_group(out) svg.footer(out)
def visualize(doc_id, segmentations, compare=[], tick_masses=None, highlight_masses=None): "Given segmentations, return an SVG visualization" [coders, mass_lists] = zip(*sorted(segmentations.items())) index_lists, m = masses_to_indexes(mass_lists) if tick_masses: tick_indexes, tick_m = masses_to_indexes(tick_masses) assert tick_m == m ticks = [ svg.tick(i) for i in tick_indexes[0] ] else: ticks = [] if highlight_masses: highlight_indexes, highlight_m = masses_to_indexes(highlight_masses) assert highlight_m == m offset = (0 if sum(highlight_masses[0][0::2]) > sum(highlight_masses[0][1::2]) else 1) highlights = [ svg.highlight(y,l) for y,l in zip([0] + highlight_indexes[0], highlight_masses[0])[offset::2] ] else: highlights = [] [lines,labels] = zip(*[ (svg.line(coder_index, coder, index, dashed=True), svg.label(coder_index, index, index)) for coder_index, coder in enumerate(coders) for index in index_lists[coder_index] ]) comparisons = list(chain(*[ comparison_lines(c, len(segmentations), m) for c in compare ])) return (svg.header(len(segmentations), m+1) + ''.join(highlights) + ''.join(ticks) + ''.join(lines) + ''.join(comparisons) + ''.join(labels) + svg.foot)
def render(self, handle=sys.stdout): handle.write( svg.header( "Helena", "scarf", width=self.width * self.pixel, height=self.length * self.pixel, )) height_offset = 0 for block in self.pieces: handle.write(svg.group_begin()) for r in range(block.height): for c in range(self.width): props = { "fill": "red" if block.data[r][c] else "white", "opacity": 1, "stroke": "none", } handle.write( svg.rect( x=c * self.pixel, y=(height_offset + r) * self.pixel, width=self.pixel, height=self.pixel, style=props, )) height_offset += block.height handle.write(svg.group_end()) handle.write(svg.footer())
def write_polygon_projection_svg(f, facepaths, sheetwidth, padding, use_numbers, use_map, center_dot, comment): x, y = padding, padding w, cur_h = 0., 0. pos = [] for i, face in enumerate(facepaths): min_x, min_y, max_x, max_y = face['bbox'] face_w, face_h = max_x-min_x, max_y-min_y if x + face_w > sheetwidth: y += cur_h + padding x, cur_h = padding, 0. pos.append( (x-min_x, y-min_y) ) cur_h = max(cur_h, face_h) x += face_w + padding w = max(w, x) h = y + cur_h + padding w, h = int(math.ceil(w)), int(math.ceil(h)) f.write(svg.header(w,h)) f.write('<title><![CDATA['+comment+']]></title>') for i, face in enumerate(facepaths): x, y = pos[i] borders_path = svg.polygon_path(face['borders']) # borders_path = svg.polygon_path(face['borders']) + ''.join(svg.polygon_path(s) for s in face['slots']) projection_path = svg.polygon_multipath(face['projection']) borders = svg.path( borders_path, style=cut ) if use_map: engraving = svg.group( svg.path( borders_path, style=engrave )+ svg.path( projection_path, style=engrave ), id='engrave_'+str(i) ) else: engraving = '' if use_numbers: text = svg.text(0,2.5, str(i), style=commentstyle+';'+textstyle ) for n, a, b in zip(face['neighbours'], face['points'], face['points'][1:]+face['points'][:1]): x1, y1 = a x2, y2 = b dx, dy = (x1+x2)/3., (y1+y2)/3.+1.5 text += svg.text(dx,dy, str(n), style=commentstyle+';'+smalltextstyle ) else: text = '' if center_dot: dot = svg.circle(.1, style=cut) else: dot = '' f.write(svg.group( svg.group(borders + engraving) + text + dot, transform='translate('+str(x)+' '+str(y)+')', id='face_'+str(i) )) f.write(svg.footer())
def header(self): print( svg.header( "Helena", "scarf", width=self.width * self.pixel, height=self.height * self.pixel, ))
def display(in_path: str, node_map: Dict[int, ET.Element], geo_bounds: Tuple[float, float, float, float], pixel_bounds: Tuple[int, int], graph: Dict[int, Set[int]], blocks: List[List[int]], pixel_blocks: List[List[int]], special_node_ref: int): # file crap title = '.'.join(os.path.basename(in_path).split('.')[:-1]) out_fn = title + '-graph.html' out_path = os.path.join(os.path.dirname(in_path), out_fn) # extract points and lines geo_lines = [] # type: List[Line] geo_points = [] # type: List[Point] for node_id, neighbor_ids in graph.items(): node = node_map[node_id] geo_points.append( (float(node.attrib['lat']), float(node.attrib['lon']))) for neighbor_id in neighbor_ids: neighbor = node_map[neighbor_id] geo_lines.append([ (float(node.attrib['lat']), float(node.attrib['lon'])), (float(neighbor.attrib['lat']), float(neighbor.attrib['lon'])), ]) # turn each block (node list) into geo poly # geo_blocks = [] # for block in blocks: # geo_block = [] # for node_id in block: # node = node_map[node_id] # geo_block.append((float(node.attrib['lat']), float(node.attrib['lon']))) # geo_blocks.append(geo_block) # extract special point coords special_node = node_map[special_node_ref] geo_special_point = (float(special_node.attrib['lat']), float(special_node.attrib['lon'])) # convert # pixel_blocks = geo.convert_polys(geo_bounds, pixel_bounds, geo_blocks) pixel_lines = geo.convert_polys(geo_bounds, pixel_bounds, geo_lines) pixel_points = geo.convert_points(geo_bounds, pixel_bounds, geo_points) pixel_special_point = geo.convert_points(geo_bounds, pixel_bounds, [geo_special_point])[0] # render contents = '\n'.join([ svg.header(pixel_bounds), svg.lines(pixel_lines), svg.circles(pixel_points), svg.polygons(pixel_blocks), # svg.circles([pixel_special_point], '#feb24c', 5), svg.footer(), ]) print('Saving to "{}"'.format(out_path)) with open(out_path, 'w') as f: f.write(contents)
def har_text_svg(text, font_size=72, margin=72, center=False, style=har_style, glyph_cache=[], f=sys.stdout): scale = (font_size/float(font.units_per_em)) top, right, bottom, left = margin+font.ascent*scale, margin, margin-font.descent*scale, margin (svg_text, w, h) = get_multiline(text, style, center) print >>f, svg.header(w*scale + left + right, h*scale + top + bottom) print >>f, svg.group(svg_text, "translate(%g %g) scale(%g)" % ( left, top, scale ) ) print >>f, svg.footer()
def write_slices(data, num_slices, output_path): """Découpe le modèle 3D en tranches et écrit le résultat dans des fichiers SVG. """ height = abs(data['zmax'] - data['zmin']) slices = [ data['zmin'] + i * height / (num_slices + 1) for i in range(1, num_slices + 1) ] for i, height in enumerate(slices): print('Création de la tranche numéro', i) path = os.path.join(output_path, 'slice_{}.svg'.format(i)) file_ = open(path, 'w') svg_width = int(abs(data['xmax'] - data['xmin'])) + 10 svg_height = int(abs(data['ymax'] - data['ymin'])) + 10 file_.write(header(svg_width, svg_height)) for triangle in data['triangles']: segment = [] for side in itertools.combinations(triangle.vertices, 2): if intersect(height, side): xa, ya, za = side[0].position xb, yb, zb = side[1].position if zb - za != 0: c = (height - za) / (zb - za) vertex = Vertex( (xa + c * (xb - xa), ya + c * (yb - ya), height)) segment.append(vertex) else: print('divide by 0') if len(segment) > 0: file_.write( line(segment[0].x - data['xmin'], segment[0].y - data['ymin'], segment[1].x - data['xmin'], segment[1].y - data['ymin'])) file_.write(footer()) file_.close()
jagged_longedge(c, d, angle, thickness, overhang, overcut), jagged_shortedge(d, a, angle, thickness, overhang, overcut), ) return [ c for e in edges for c in e ] def slots(radius): edges = [] a, b, c, d = ( (x*radius, y*radius) for x,y in dhxdron_deltoid_2d_coords() ) return ( slot_short(a, b, native_scale), slot_long(b, c, native_scale), slot_long(c, d, native_scale), slot_short(d, a, native_scale), ) style = 'stroke:none;fill:#0000ff;opacity:.3' print svg.header(radius*2,radius*2) print '<g transform="translate('+str(radius)+' '+str(radius)+')">' print svg.circle(radius, style) print svg.path( svg.polygon_path(shape(radius=radius, thickness=thickness)), style) for slot in slots(radius=radius): print svg.path( svg.polygon_path(slot), style) print '</g>' print svg.footer()