def recognize_crash(self): front = list( bresenham(self.left_top_padding[0], self.left_top_padding[1], self.right_top_padding[0], self.right_top_padding[1])) left = list( bresenham(self.left_top_padding[0], self.left_top_padding[1], self.left_bottum_padding[0], self.left_bottum_padding[1])) right = list( bresenham(self.right_bottum_padding[0], self.right_bottum_padding[1], self.right_top_padding[0], self.right_top_padding[1])) back = list( bresenham(self.right_bottum_padding[0], self.right_bottum_padding[1], self.left_bottum_padding[0], self.left_bottum_padding[1])) total_padding_location = np.concatenate([left, right, back]) border_pixel_color = [] for each_location in total_padding_location: try: border_pixel_color.append( self.color_detector( self.screen.get_at( self.transformer.transform(each_location)))) except: border_pixel_color.append(True) # print('border_pixel_color : ', border_pixel_color) for i in border_pixel_color: if i: return True return False
def sense_init(self): #a main/control method used to call all necessary subroutines #executing this method will provide the agent with a full set of sensor information in direction agent facing #first, we have to find the outer edges of the agent's field of view (leftEdge, rightEdge) = self.cast_boundary_rays() #print("Left Edge: ", leftEdge) leftPath = list( bresenham(self.get_agentx(), self.get_agenty(), leftEdge[0], leftEdge[1])) rightPath = list( bresenham(self.get_agentx(), self.get_agenty(), rightEdge[0], rightEdge[1])) print("Boundary Rays: ") for i in range(0, self.rows): for j in range(0, self.cols): if (i, j) in leftPath or (i, j) in rightPath: print(".", end='') else: print(self.grid[i][j], end='') print() #print("Initial left path ", leftPath) #now that the paths have been created, we must trace between cooresponding points on each line #since the FOV is bounded by two lines with a slope of 1, we can guarantee that there will #be exactly one point in the bounding line on either side of the FOV return self.sense(leftPath, rightPath)
def generate_visiblity_map(*pos_obs): vis = np.zeros((height, width)) elev_obs = e[pos_obs] vis[pos_obs] = 1 for w in range(width): visiblity(bresenham(*pos_obs, w, 0), vis, elev_obs) visiblity(bresenham(*pos_obs, w, height - 1), vis, elev_obs) for h in range(height): visiblity(bresenham(*pos_obs, width - 1, h), vis, elev_obs) visiblity(bresenham(*pos_obs, 0, h), vis, elev_obs) plt.imshow(e, cmap=cm1, interpolation="nearest", vmin=0, vmax=1) plt.colorbar() cm2.set_under(alpha=0) plt.imshow(vis, cmap=cm2, interpolation="nearest", vmin=0.001, vmax=1, alpha=0.6) # plt.show() plt.savefig(f"visiblity_{pos_obs}.png", dpi=300, bbox_inches="tight") plt.close() vis[vis > 0.1] = 1 return vis
def Area_Search(search_area, kernel, midpoint): change = False for n in range(0, (kernel - 1) * 2): if n < kernel: coordinates = [0, n] else: coordinates = [n - kernel + 1, kernel - 1] points = np.array( list(bresenham(coordinates[0], coordinates[1], midpoint, midpoint)))[0:midpoint] anti_points = np.array( list( bresenham(kernel - 1 - coordinates[0], kernel - 1 - coordinates[1], midpoint, midpoint)))[0:midpoint] for x in range(0, midpoint): if x == 0: points_value = search_area[points[x][0]][points[x][1]] anti_points_value = search_area[anti_points[x][0]][ anti_points[x][1]] else: points_value = np.hstack( (points_value, search_area[points[x][0]][points[x][1]])) anti_points_value = np.hstack( (anti_points_value, search_area[anti_points[x][0]][anti_points[x][1]])) if np.any(points_value == 255) == True: if np.any(anti_points_value == 255) == True: change = True break return change
def drawlines(x1, y1): pixelsDrawn = [] r = 10 x1 = int(start_point[0] + x1) y1 = int(start_point[1] + y1) # Use parametric equations t_degree = random.randint(0, 360) t_radians = math.radians(t_degree) x2 = x1 + int(r * (math.cos(t_radians))) y2 = y1 + int(r * (math.sin(t_radians))) pyautogui.moveTo(x1, y1) pyautogui.dragTo(x2, y2, button='left') pixelsDrawn = pixelsDrawn + (list(bresenham(x1, y1, x2, y2))) stepsize = 2 # moves over 2 pixels miniRsum = 0 while (miniRsum < r): x1 = x1 + int(stepsize * (math.cos(t_radians + (math.pi / 2)))) y1 = y1 + int(stepsize * (math.sin(t_radians + (math.pi / 2)))) x2 = x1 + int(r * (math.cos(t_radians))) y2 = y1 + int(r * (math.sin(t_radians))) miniRsum = miniRsum + stepsize pyautogui.moveTo(x1, y1) pyautogui.dragTo(x2, y2, button='left') pixelsDrawn = pixelsDrawn + (list(bresenham(x1, y1, x2, y2))) no_duplicate_list = [] #Removes all duplicates in the list. for x in pixelsDrawn: if x not in no_duplicate_list: no_duplicate_list.append(x) #[no_duplicate_list.append(x) for x in pixelsDrawn if x not in no_duplicate_list] return no_duplicate_list
def main(screen): key = "" point1 = [0, 0] point2 = [8, 8] while True: grid = [[' ' for x in range(0, curses.COLS)] for x in range(0, curses.LINES - 1)] bresenham.bresenham(point1, point2, grid) screen.clear() print_grid(grid, screen) screen.addstr(curses.LINES - 1, 0, "A" + str(point1) + " B" + str(point2)) key = screen.getkey() if key == "w" and point1[1] > 0: point1[1] -= 1 elif key == "s" and point1[1] < curses.LINES - 2: point1[1] += 1 elif key == "a" and point1[0] > 0: point1[0] -= 1 elif key == "d" and point1[0] < curses.COLS - 1: point1[0] += 1 elif key == "KEY_UP" and point2[1] > 0: point2[1] -= 1 elif key == "KEY_DOWN" and point2[1] < curses.LINES - 2: point2[1] += 1 elif key == "KEY_LEFT" and point2[0] > 0: point2[0] -= 1 elif key == "KEY_RIGHT" and point2[0] < curses.COLS - 1: point2[0] += 1 elif key == "q": break
def test_min_slope_two_way(): assert tuple(bresenham(0, 0, 10, 1)) == ((0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1)) assert tuple(bresenham(10, 1, 0, 0)) == ((10, 1), (9, 1), (8, 1), (7, 1), (6, 1), (5, 0), (4, 0), (3, 0), (2, 0), (1, 0), (0, 0))
def amostras_textura(formas, d): for forma in formas: i = 0 while i < len(forma.pontos): x1, y1 = forma.pontos[i - 1][0], forma.pontos[i - 1][1] p1 = (forma.pontos[i - 1][0], forma.pontos[i - 1][1]) x3, y3 = forma.pontos[i][0], forma.pontos[i][1] p3 = (forma.pontos[i][0], forma.pontos[i][1]) if i == (len(forma.pontos) - 1): p2 = (forma.pontos[0][0], forma.pontos[0][1]) x2, y2 = forma.pontos[0][0], forma.pontos[0][1] #print("p3", p3) else: p2 = [forma.pontos[i + 1][0], forma.pontos[i + 1][1]] x2, y2 = forma.pontos[i + 1][0], forma.pontos[i + 1][1] k = float(((y2 - y1) * (x3 - x1) - (x2 - x1) * (y3 - y1)) / ((y2 - y1)**2 + (x2 - x1)**2)) x4 = float(x3 - k * (y2 - y1)) y4 = float(y3 + k * (x2 - x1)) p4 = [round(x4), round(y4)] #print(p4) #print(line1) diferenca = np.array(p3) - np.array(p4) #print(diferenca) p6 = np.array(p3) + diferenca #p4 = np.array(p4) - diferenca #print("P4:", p4) line = list(bresenham(p4[0], p4[1], p6[0], p6[1])) while len(line) <= d: p6 = np.array(p6) + diferenca p4 = np.array(p4) - diferenca #print("P4:", p4) #print("PONTOS:", p3, p4, "\n") line = list(bresenham(p4[0], p4[1], p6[0], p6[1])) #print(line) #print(p1,p3,p2) j = line.index(p3) k = j - int(d / 2) j = j + int(d / 2) list_aux = [] while k <= j: list_aux.append(line[k]) k += 1 forma.amostra.append(list_aux) i += 1 autovalores, autovetores = primeira_derivada(formas) return autovalores, autovetores
def sense_init(self): #a main/control method used to call all necessary subroutines #executing this method will provide the agent with a full set of sensor information in direction agent facing #first, we have to find the outer edges of the agent's field of view (leftEdge, rightEdge) = self.cast_boundary_rays() leftPath = list(bresenham(self.agentx, self.agenty, leftEdge[0], leftEdge[1])) rightPath = list(bresenham(self.agentx, self.agenty, rightEdge[0], rightEdge[1])) #now that the paths have been created, we must trace between cooresponding points on each line #since the FOV is bounded by two lines with a slope of 1, we can guarantee that there will #be exactly one point in the bounding line on either side of the FOV return self.sense(leftPath, rightPath)
def prune_path_bresenham(grid, path): pruned_path = [p for p in path] i = 0 while i < len(pruned_path) - 2: p1 = pruned_path[i] p2 = pruned_path[i + 1] p3 = pruned_path[i + 2] cells = list(bresenham(int(p1[0]), int(p1[1]), int(p3[0]), int(p3[1]))) hit = False for c in cells: # Next check if we're in collision if grid[c[0], c[1]] == 1: hit = True break # If the edge does not hit on obstacle # remove middle point if not hit: # array to tuple for future graph creation step) pruned_path.remove(pruned_path[i + 1]) return pruned_path
def create_grid_and_edges(data, drone_altitude, safety_distance, float_precision=4): """ Returns a grid representation of a 2D configuration space along with Voronoi graph edges given obstacle data and the drone's altitude. """ grid, offset, centers = create_grid(data, drone_altitude, safety_distance) # create a voronoi graph based on # location of obstacle centres graph = Voronoi(centers) # check each edge from graph.ridge_vertices for collision edges = [] for v in graph.ridge_vertices: p1 = np.around(graph.vertices[v[0]], float_precision) p2 = np.around(graph.vertices[v[1]], float_precision) hit = False if p1[0] < 0 or p1[0] >= grid.shape[0] or p1[1] < 0 or p1[1] >= grid.shape[1] \ or p2[0] < 0 or p2[0] >= grid.shape[0] or p2[1] < 0 or p2[1] >= grid.shape[1]: continue for cell in bresenham(int(p1[0]), int(p1[1]), int(p2[0]), int(p2[1])): if grid[cell[0], cell[1]]: hit = True break # If the edge does not hit on obstacle # add it to the list if not hit: edges.append((p1.tolist(), p2.tolist())) return grid, offset, edges
def prune_path(grid, path): """ Using Bresenham module to reduce waypoints from path """ pruned_path = [p for p in path] i = 0 while i < len(pruned_path) - 2: p1 = pruned_path[i] p2 = pruned_path[i + 1] p3 = pruned_path[i + 2] """ if the line between p1 and p2 doesn't hit an obstacle remove the 2nd point. The 3rd point now becomes the 2nd point and the check is redone with a new third point on the next iteration.""" if all( (grid[pp] == 0) for pp in bresenham(p1[0], p1[1], p3[0], p3[1])): """ Something subtle here but we can mutate `pruned_path` freely because the length of the list is checked on every iteration.""" pruned_path.remove(p2) else: i += 1 return pruned_path
def scan_callback(self, scan): """ Update the map on every scan callback. """ # Fill some cells in the map just so we can see that something is # being published. Lresol = 1 / myRes r = scan.ranges[0] xt = [self.position[0] + 1, self.position[1] + 1, self.position[2]] # for k in range(0,len(scan.ranges)-1): scanAngles = np.linspace(scan.angle_max, scan.angle_min, len(scan.ranges)) lidar_local = np.array([ xt[0] + scan.ranges * np.cos(scanAngles + xt[2]), xt[1] - (scan.ranges * np.sin(scanAngles + xt[2])) ]) # print len(lidar_local[1]) xtg = [int(np.ceil(xt[0] * Lresol)), int(np.ceil(xt[1] * Lresol))] self._map.grid[xtg[1], xtg[0]] = 0 # set the robot position grid as empty for k in range(0, len(scan.ranges) - 1): if scan.ranges[k] < scan.range_max: rtl = np.ceil(lidar_local[:, k] * Lresol) rtli = [0, 0] rtli[0] = int(rtl[0]) rtli[1] = int(rtl[1]) l = bresenham(xtg, rtli) self.EISM(l.path, scan.ranges[k]) # Now that the map is updated, publish it! rospy.loginfo("Scan is processed, publishing updated map.") self.publish_map()
def bres(path, grid): i = 0 while True: if i > (len(path) - 3): break p1 = path[i] j = len(path) - 1 while True: if j == (i + 1): break p2 = path[j] cells = list( bresenham(int(p1[0]), int(p1[1]), int(p2[0]), int(p2[1]))) in_collision = False for c in cells: if c[0] < 0 or c[1] < 0 or c[0] >= grid.shape[0] or c[ 1] >= grid.shape[1]: in_collision = True break if grid[c[0], c[1]] == 1: in_collision = True break if in_collision == False: for r in range(i + 1, j): path.remove(path[i + 1]) break else: j = j - 1 i = i + 1 return path
def prune_path(self,path,grid): result = [] flags = [0] * len(path) for i , p in enumerate(path): if flags[i] == 0: for j , q in enumerate(path): if j > i + 1: pathClear = True if flags[j] == 0: cells = list(bresenham(p[0], p[1], q[0], q[1])) for cell in cells: if grid[ cell[0],cell[1] ] == 1: pathClear = False break if pathClear: #print("Path IS clear between " , p,q) for k in range(i+1,j): flags[k] = 1 for i , f in enumerate(flags): if f == 0: result.append(path[i]) return result
def prune_path_bres(path, grid): """ Prune grid path using Bresenham ray-tracing method. Requires grid to check if intermediate paths are obstacle-free :param path: :param grid: :return: """ pruned_path = [path.pop(0)] p2 = path.pop(0) for i, p3 in enumerate(path): p1 = pruned_path[-1] for p in list(bresenham(p1[0], p1[1], p3[0], p3[1])): if grid[p[0], p[1]] > 0.0: # collision from p1 to p3 # use p2 as last point working well pruned_path.append(p2) p2 = p break if i == len(path): pruned_path.append(p3) break # p1 to p3 has no collisions, so remove p2 p2 = p3 pruned_path.append(path[-1]) return pruned_path
def check_connection(img): indent = 0 success = True #new_prediction = img #print(np.unique(img.float().round().detach().cpu().numpy())) inds = np.where( np.array(img.float().round().detach().tolist()).astype('uint8') == 0) if len(inds) < 0: return False, 1 prev_x, prev_y = sorted(zip(inds[1], inds[0]))[0] for x, y in sorted(zip(inds[1], inds[0]))[1:]: if abs(prev_x - x) <= 1 and abs(prev_y - y) <= 1: prev_x = x prev_y = y continue if prev_x == x: prev_y = y continue indent += 1 # print(list(bresenham(prev_x, prev_y, x, y))) for cell in list(bresenham(prev_x, prev_y, x, y))[1:-1]: print(img[cell[1], cell[0]]) if img[cell[1], cell[0]] == 1: success = False else: img[cell[1], cell[0]] = 0 prev_x = x prev_y = y return success, indent
def bresenham_check(p1, p3, grid): cells = list(bresenham(p1[0], p1[1], p3[0], p3[1])) # make sure that cells are not flagged as obstacle for cell in cells: if grid[cell[0],cell[1]] == 1: return False return True
def pixel_list(self): pixel_list = list( bresenham(self.start_x, self.start_y, self.end_x, self.end_y)) # Ignores first and last pixel pixel_list.pop(0) pixel_list.pop() return pixel_list
def connect(self): '''Connects caves using bresenham lines.''' # TODO: Add better connection, using center bresenhams and cave detection. cavesWalls = self.cavesWalls while len(cavesWalls) > 0: currentCaveWalls = cavesWalls.pop() for wall in currentCaveWalls: if len(cavesWalls) > 1: randCave = random.randint(0,len(cavesWalls)-1) randWall = cavesWalls[randCave][random.randint(0,len(cavesWalls[randCave])-1)] else: randWall = self.center bresen = list(map(TRANSPOSE,list(bresenham(wall.x,wall.y,randWall.x,randWall.y)))) active = False for i,point in enumerate(bresen[1:]): if self.cavesReferences.get(point,-1) == self.cavesReferences[wall]: break elif point in self.cavesReferences and self.cavesReferences[point] != self.cavesReferences[wall]: bresen = bresen[:i+1] active = True break if active: for point in bresen: for neighbor in FLATTEN([[ADD(point,Tile(i,j)) for i in range(-1,2)] for j in range(-1,2)]): if self.level[neighbor.y][neighbor.x]: self.level[neighbor.y][neighbor.x] = False break
def _representation(self): x, y = (self._endpos - self._startpos).xy # TODO better representation of straight line (using ASCII chars)? if abs(x) > 0: angle = atan(y / x) else: angle = pi / 2 if angle < radians(-75): linechar = '|' if angle >= radians(-75) and angle <= radians(-52): linechar = '.' elif angle > radians(-52) and angle <= radians(-37): linechar = '/' elif angle > radians(-37) and angle <= radians(-15): linechar = '.' elif angle > radians(-15) and angle <= radians(15): linechar = '-' elif angle > radians(15) and angle <= radians(37): linechar = '.' elif angle > radians(37) and angle <= radians(52): linechar = '\\' elif angle > radians(52) and angle <= radians(75): linechar = '.' elif angle > radians(75): linechar = '|' else: linechar = '?' repr = dict() line = bresenham(self._startpos.x, self._startpos.y, self._endpos.x, self._endpos.y) for coord in line: pos = Pos(coord[0], coord[1]) repr[pos] = linechar self._repr = repr
def updatemap(self, scandata, angle_min, angle_max, angle_increment, range_min, range_max, pose): robot_origin = int(pose[0]) + int(math.ceil(self.width / self.resolution) * pose[1]) centreray = len(scandata) / 2 + 1 for i in range(len(scandata)): if not math.isnan(scandata[i]): beta = (i - centreray) * angle_increment px = int(float(scandata[i]) * cos(beta - pose[2]) / self.resolution) py = int(float(scandata[i]) * sin(beta - pose[2]) / self.resolution) l = bresenham.bresenham([0, 0], [px, py]) for j in range(len(l.path)): lpx = self.map_origin[0] + pose[0] + l.path[j][0] * self.resolution lpy = self.map_origin[1] + pose[1] + l.path[j][1] * self.resolution if (0 <= lpx < self.width and 0 <= lpy < self.height): index = self.origin + int(l.path[j][0] + math.ceil(self.width / self.resolution) * l.path[j][1]) if scandata[i] < self.max_scan_range * range_max: if (j < len(l.path) - 1): self.logodds[index] += self.pfree else: self.logodds[index] += self.pocc else: self.logodds[index] += self.pfree if self.logodds[index] > self.max_logodd: self.logodds[index] = self.max_logodd elif self.logodds[index] < -self.max_logodd: self.logodds[index] = -self.max_logodd if self.logodds[index] > self.max_logodd_belief: self.localmap[index] = 100 else: self.localmap[index] = 0 self.localmap[self.origin] = 100.0
def create_graph(grid, centres): vor_graph = Voronoi(centres) edges = [] gr = nx.Graph() for v in vor_graph.ridge_vertices: p1 = vor_graph.vertices[v[0]] p2 = vor_graph.vertices[v[1]] cells = list(bresenham(int(p1[0]), int(p1[1]), int(p2[0]), int(p2[1]))) hit = False for c in cells: # First check if we're off the map if np.amin(c) < 0 or c[0] >= grid.shape[0] or c[1] >= grid.shape[1]: hit = True break # Next check if we're in collision if grid[c[0], c[1]] == 1: hit = True break # If the edge does not hit on obstacle # add it to the list if not hit: # array to tuple for future graph creation step) p1 = (p1[0], p1[1]) p2 = (p2[0], p2[1]) edges.append((p1, p2)) gr.add_edge(p1, p2, weight=1) return edges, gr
def run(self, path): pruned_path = [p for p in path] i = 0 while i < len(pruned_path) - 2: p1 = pruned_path[i] p2 = pruned_path[i + 1] p3 = pruned_path[i + 2] cells = list( bresenham(int(p1[0]), int(p1[1]), int(p3[0]), int(p3[1]))) hit = False # Collision check for c in cells: # First check if we're off the map if np.amin(c) < 0 or c[0] >= self.grid.shape[0] or c[ 1] >= self.grid.shape[1]: hit = True break # Next check if we're in collision if self.grid[c[0], c[1]] == 1: hit = True break # If the 3 points are in a line remove # the 2nd point. # The 3rd point now becomes and 2nd point # and the check is redone with a new third point # on the next iteration. if not hit: # Something subtle here but we can mutate # `pruned_path` freely because the length # of the list is check on every iteration. pruned_path.remove(pruned_path[i + 1]) else: i += 1 return pruned_path
def prune_path(path: List[Tuple[int, int, int]]) -> List[Tuple[int, int, int]]: """Prune path of nodes using the Bresenham algorithm. :param path: A fully connected path. :return: A pruned path, removing unnecessary points. """ pruned_path = [] for i, p in enumerate(path): if (i == 0) or (i == (len(path) - 1)): pruned_path.append(p) else: cells = list( bresenham( path[i - 1][0], path[i - 1][1], path[i + 1][0], path[i + 1][1], )) if p not in cells: pruned_path.append(p) print("Length of path: {}, length of pruned path: {}.".format( len(path), len(pruned_path))) return pruned_path
def drawPNG (vector_images, side=256, time=None): raster_image = np.ones((side, side), dtype=np.uint8); vector_sketch = list() prevX, prevY = None, None; start_time = vector_images[0]['timestamp'] if time is None: time = vector_images[-1]['timestamp'] - start_time for points in vector_images: if (points['timestamp'] - start_time)/1000 > time: break x, y = map(float, points['coordinates']) x = int(x * side); y = int(y * side) pen_state = list(map(int, points['pen_state'])) if not (prevX is None or prevY is None): cordList = list(bresenham(prevX, prevY, x, y)) for cord in cordList: if (cord[0] > 0 and cord[1] > 0) and (cord[0] < side and cord[1] < side): raster_image[cord[1], cord[0]] = 0 if pen_state == [0, 1, 0]: prevX = x; prevY = y vector_sketch.append([x, y, 0]) elif pen_state == [1, 0, 0]: prevX = None; prevY = None; vector_sketch.append([x, y, 1]) else: raise ValueError('pen_state not accounted for') else: prevX = x; prevY = y; # invert black and white pixels and dialate raster_image = (1 - cv2.dilate(1-raster_image, np.ones((3,3),np.uint8), iterations=1))*255 return raster_image, vector_sketch, time/1000
def find_open_edges_voronoi(graph, grid):#?? """ Finds open edges from `graph` and `grid` """ edges = [] for v in graph.ridge_vertices: p1 = graph.vertices[v[0]] p2 = graph.vertices[v[1]] cells = list(bresenham(int(p1[0]), int(p1[1]), int(p2[0]), int(p2[1]))) hit = False for c in cells:#cells?? # First check if we're off the map if np.amin(c) < 0 or c[0] >= grid.shape[0] or c[1] >= grid.shape[1]: hit = True break # Next check if we're in collision if grid[c[0], c[1]] == 1:#?? hit = True break # If the edge does not hit on obstacle # add it to the list if not hit: # array to tuple for future graph creation step) p1 = (p1[0], p1[1])#?? p2 = (p2[0], p2[1]) edges.append((p1, p2)) return edges
def max_distance(posA, posB, width, height, skip_up=True): """ see if it is possible to move between two points (returns the furthest distance) """ x, y = posA x_dest, y_dest = posB cross = list(bresenham(x, y, x_dest, y_dest))[1:] x_dest = x_prev = x y_dest = y_prev = y #print('{} ==> {}'.format(posA, posB)) #print('cross {}'.format(cross)) #print('cells {}'.format(Globals.instance.cells)) for p in cross: # see if any the next points will hit an obstacle (coming down) next_area = to_area(p[0], p[1], width, height, bottom_only=True) #print(' next area {}'.format(next_area)) clear = True if p[1] > y_prev or skip_up is False: for pn in next_area: if pn in Globals.instance.cells and is_wall( pn, cells=Globals.instance.cells[pn]): #print(' there is something at {}'.format(pn)) clear = False break if clear: x_dest = int(p[0]) y_dest = int(p[1]) else: break x_prev = p[0] y_prev = p[1] #print('jumping to {}'.format((x_dest,y_dest))) return x_dest, y_dest
def prune_path_bres(path, grid): if path is not None: pruned_path = [path[0]] s, f = 0, 2 while f < len(path): cells = list(bresenham(path[s][0], path[s][1], path[f][0], path[f][1])) obstacle = False for c in cells: if grid[c] == 1: obstacle = True break if obstacle == True: pruned_path.append(path[f-1]) s = f - 1 f = f + 1 pruned_path.append(path[-1]) else: pruned_path = path return pruned_path
def compute_rays(x0, y0, x1, y1, rays): ray = list(bresenham(x0, y0, x1, y1)) # Duplicate the ray so that x and y are not incremented at the same time duplicated = False ray_x = [] # x incremented before y ray_y = [] # y incremented before x x = ray[0][0] y = ray[0][1] for tile in ray[1:]: if tile[0] != x and tile[1] != y: duplicated = True ray_x.append((tile[0], y)) ray_x.append((tile[0], tile[1])) ray_y.append((x, tile[1])) ray_y.append((tile[0], tile[1])) else: ray_x.append((tile[0], tile[1])) ray_y.append((tile[0], tile[1])) x = tile[0] y = tile[1] rays.append(ray_x) if duplicated: rays.append(ray_y) return rays
def dragLineToPoint(self, point): """ Calculates the new point and adds it to self.draggedPositions. Called by mouseDown and mouseDrag """ if getattr(self.brushMode, 'draggableBrush', True): if self.lineToolKey: if len(self.draggedPositions): points = bresenham.bresenham(self.draggedPositions[0], point) self.draggedPositions = [self.draggedPositions[0]] self.draggedPositions.extend(points[::self.options['Minimum Spacing']][1:]) elif self.lastPosition is not None: points = bresenham.bresenham(self.lastPosition, point) self.draggedPositions.extend(points[::self.options['Minimum Spacing']][1:]) else: self.draggedPositions.append(point) else: self.draggedPositions = [point]
def obstruction(start, end, team2_robot_state): team2_x = param.meterToPixel(team2_robot_state.pos_x_est) team2_y = param.meterToPixel(team2_robot_state.pos_y_est) ray = br.bresenham([param.meterToPixel(start.x), param.meterToPixel(start.y)], [param.meterToPixel(end.x), param.meterToPixel(end.y)]) for point in ray.path: print point[0], "," , point[1] if point[0] < (team2_x + 30) and point[0] > (team2_x - 30) and \ point[1] < (team2_y + 30) and point[1] > (team2_y - 30): return True return False
def updateVisible(self, player_x, player_y, square_x, square_y): """ Tiles have three states: invisible, remembered, and bright. Invisible tiles appear as black. Remembered tiles appear as a slightly-darkened image. Lit tiles appear normal, but are darkened proportionately to their brightness. Transitions: Invisible -> bright: if visibility criteria are met. Remembered -> bright: if visibility criteria are met. Bright -> remembered: if visibility criteria are not met. No other transitions are possible. Visibility: A tile is visible if: It is within range of the player's light, and The player view-casting algorithm (see below) says so. Player view-casting: For each tile, calculate the Bresenham line to the player. Walk this line, by examining every tile between the line and the player, not including the target tile but including the tile the player is standing on. If the line intersects any opaque tiles, the target tile is not viewable. A simple optimisation would be to start with the tiles closest to the player and skip view casting for portions of the display if a tile is opaque. For example, the player is surrounded by 8 tiles; if one tile is opaque then (360 / 8) = 45 degrees of visual field are obscured. """ try: targetSquare = self[square_y][square_x] except IndexError: return #print "do bres", player_x, player_y, square_x, square_y for bres_x, bres_y in bresenham(player_x, player_y, square_x, square_y): if (bres_x == player_x and bres_y == player_y) or (bres_x == square_x and bres_y == square_y): pass else: try: square = self[bres_y][bres_x] except IndexError: continue if square.checkattr('transp') is False: # Blocked! targetSquare.setVisible(False) break else: targetSquare.setVisible(True)
def drawLine(angle, r, g, b): end_x = (math.cos(angle) * 20.0) + center_x end_y = (math.sin(angle) * 20.0) + center_y for x, y in bresenham(center_x, center_y, int(end_x), int(end_y)): if x > 0 and x <= 15 and y > 0 and y <= 15: unicorn.set_pixel(x, y, r, g, b)
plt.grid() plt.axis('equal') plt.xlabel("X") plt.ylabel("Y") plt.title("Integer based Bresenham algorithm") plt.show() import sys !{sys.executable} -m pip install bresenham from bresenham import bresenham # Note: you can run this for any (x1, y1, x2, y2) line = (0, 0, 7, 5) cells = list(bresenham(line[0], line[1], line[2], line[3])) print(cells) plt.plot([line[0], line[2]], [line[1], line[3]]) for q in cells: plt.plot([q[0], q[0]+1], [q[1], q[1]], 'k') plt.plot([q[0], q[0]+1], [q[1]+1, q[1]+1], 'k') plt.plot([q[0], q[0]], [q[1],q[1]+1], 'k') plt.plot([q[0]+1, q[0]+1], [q[1], q[1]+1], 'k') plt.grid() plt.axis('equal') plt.xlabel("X") plt.ylabel("Y")
def __init__(self, worm_lost, birth_point, name=None): self.worm_lost = worm_lost self.birth_point = birth_point self.center_line = iter(bresenham(birth_point, worm_lost.ellipse[0])) # Create line self.name = name