def __init__(self, src_objects, start: int, end: int, time0: float, time1: float): objects = src_objects axis = ru.get_random_int_in_range(0, 2) object_span = end - start if object_span == 1: self.left = objects[start] self.right = objects[start] elif object_span == 2: if box_compare(objects[start], objects[start + 1], axis): self.left = objects[start] self.right = objects[start + 1] else: self.left = objects[start + 1] self.right = objects[start] else: objects[start:end] = sorted(objects[start:end], key=lambda x: x.min_box[axis]) mid = int(start + object_span / 2) self.left = BVHNode(objects, start, mid, time0, time1) self.right = BVHNode(objects, mid, end, time0, time1) box_left = AABB(empty, empty) box_right = AABB(empty, empty) flag_left, box_left = self.left.bounding_box(time0, time1, box_left) flag_right, box_right = self.right.bounding_box( time0, time1, box_right) if not flag_left or not flag_right: print("No bounding box in bvh_node constructor.") raise self.box = surrounding_box(box_left, box_right)
def __init__(self, obj, angle): self.obj = obj radians = deg_to_rad(angle) self.sin_theta = sin(radians) self.cos_theta = cos(radians) self.bbox = AABB() self.hasbox = obj.bounding_box(0, 1, self.bbox) _min = Point3( float('inf'), float('inf'), float('inf')) _max = Point3(float('-inf'), float('-inf'), float('-inf')) for i in range(2): for j in range(2): for k in range(2): x = i * self.bbox._max.x + (1 - i) * self.bbox._min.x y = j * self.bbox._max.y + (1 - j) * self.bbox._min.y z = k * self.bbox._max.z + (1 - k) * self.bbox._min.z newx = self.cos_theta * x + self.sin_theta * z newz = -self.sin_theta * x + self.cos_theta * z tester = Vec3(newx, y, newz) for c in range(3): _min[c] = min(_min[c], tester[c]) _max[c] = max(_max[c], tester[c]) self.bbox = AABB(_min, _max)
def main(): fpsClock = pygame.time.Clock() pygame.init() displaySurface = pygame.display.set_mode((screenWidth, screenHeight)) pygame.display.set_caption(title) blue = AABB(Vector2(60, 60), Vector2(140, 60)) red = AABB(Vector2(300, 180), Vector2(100, 180)) holdingRect = None holdingOffset = Vector2() lastMouseState = (False, False, False) gameRunning = True while (gameRunning): for event in pygame.event.get(): if (event.type == QUIT): gameRunning = False lastMouseState, holdingRect, holdingOffset = updateMouse( lastMouseState, holdingRect, holdingOffset, blue, red, minBounds, maxBounds) render(displaySurface, blue, red) renderMouse(displaySurface, holdingRect, holdingOffset) pygame.display.update() fpsClock.tick(fps) pygame.quit() sys.exit()
def split(self): half_w = self.__boundary.w / 2 half_h = self.__boundary.h / 2 x, y = self.__boundary.x, self.__boundary.y self.__n_west = QuadTree(AABB(x, y, half_w, half_h)) self.__n_east = QuadTree(AABB(x + half_w, y, half_w, half_h)) self.__s_west = QuadTree(AABB(x, y + half_h, half_w, half_h)) self.__s_east = QuadTree(AABB(x + half_w, y + half_h, half_w, half_h))
def box_compare(self, a, b, axis): box_a = AABB() box_b = AABB() if (not a.bounding_box(0, 0, box_a)) or (not b.bounding_box( 0, 0, box_b)): print('No bounding box in BvhNode constructor') return (box_a._min[axis] < box_b._min[axis])
def box_compare(a: Hittable, b: Hittable, axis: int): box_a = AABB(empty, empty) box_b = AABB(empty, empty) flag_a, box_a = a.bounding_box(0, 0, box_a) flag_b, box_b = b.bounding_box(0, 0, box_b) if not flag_a or not flag_b: print("No bounding box in bvh_node constructor") raise return box_a.minimum[axis] < box_b.minimum[axis]
def __init__(self, objects, time0, time1, start=None, end=None): self.objects = objects self.time0 = time0 self.time1 = time1 self.box = AABB() if start is None: self.start = 0 else: self.start = start if end is None: self.end = len(self.objects) else: self.end = end axis = int(uniform(0, 3)) if axis == 0: comparator = self.box_x_compare elif axis == 1: comparator = self.box_y_compare else: comparator = self.box_z_compare object_span = self.end - self.start if object_span == 1: self.left = self.objects[self.start] self.right = self.objects[self.start] elif object_span == 2: if comparator(self.objects[self.start], self.objects[self.start + 1]): self.left = self.objects[self.start] self.right = self.objects[self.start + 1] else: self.left = self.objects[self.start + 1] self.right = self.objects[self.start] else: s = sorted(self.objects[self.start:self.end + 1], key=comparator) mid = self.start + object_span / 2 self.left = BvhNode(self.objects, self.start, mid, self.time0, self.time1) self.right = BvhNode(self.objects, mid, self.end, self.time0, self.time1) box_left = AABB() box_right = AABB() if (not self.left.bounding_box(self.time0, self.time1, box_left)) or ( not self.right.bounding_box(self.time0, self.time1, box_right)): print('No bounding box in BvhNode constructor') self.box = AABB.surrounding_box(box_left, box_right)
def test_intersects(): aabb1 = AABB((0, 0), (20, 30)) aabb2 = AABB((0, 0), (20, 30)) assert(aabb1.intersects(aabb2)) aabb2 = AABB((100, 100), (200, 200)) assert(not aabb1.intersects(aabb2)) aabb2 = AABB((-5, -5), (10, 10)) assert(aabb1.intersects(aabb2)) aabb2 = AABB((5, 5), (10, 10)) assert(aabb1.intersects(aabb2)) aabb2 = AABB((-5, 5), (10, 10)) assert(aabb1.intersects(aabb2)) aabb2 = AABB((5, -5), (10, 10)) assert(aabb1.intersects(aabb2)) # Edge case: two AABBs that share exactly one edge should not be considered intersecting aabb2 = AABB((20, 0), (40, 30)) assert(not aabb1.intersects(aabb2)) # Edge case: two AABBs that share exactly one point should not be considered intersecting aabb2 = AABB((20, 30), (40, 60)) assert(not aabb1.intersects(aabb2)) with pytest.raises(TypeError): aabb1.intersects("Not a word")
def test_width_height(): aabb = AABB((0, 0), (50, 30)) assert(aabb.width == 50) assert(aabb.height == 30) aabb = AABB((0, 0), (10, 0)) assert (aabb.width == 10) assert (aabb.height == 0) aabb = AABB((0, 0), (0.1, 0.1)) assert (aabb.width == 0.1) assert (aabb.height == 0.1)
def test_inside(): aabb1 = AABB((0, 0), (50, 30)) aabb2 = AABB((0, 0), (20, 30)) assert(not aabb1.inside(aabb2)) assert(aabb2.inside(aabb1)) # Edge case: AABBs should be considered "inside" AABBs of the exact same dimensions (and vice-versa) aabb2 = aabb1 assert (aabb1.inside(aabb2)) assert (aabb2.inside(aabb1)) with pytest.raises(TypeError): aabb1.inside("Not a word")
def parse_gt(self, fn_gt): tree = ET.parse(fn_gt) root = tree.getroot() aabbs = [] # list of all axis aligned bounding boxes of current sample # go over all lines for line in root.findall("./handwritten-part/line"): # go over all words for word in line.findall('./word'): xmin, xmax, ymin, ymax = float('inf'), 0, float('inf'), 0 success = False # go over all characters for cmp in word.findall('./cmp'): success = True x = float(cmp.attrib['x']) y = float(cmp.attrib['y']) w = float(cmp.attrib['width']) h = float(cmp.attrib['height']) # aabb around all characters is aabb around word xmin = min(xmin, x) xmax = max(xmax, x + w) ymin = min(ymin, y) ymax = max(ymax, y + h) if success: aabbs.append(AABB(xmin, xmax, ymin, ymax).scale(self.loaded_img_scale, self.loaded_img_scale)) return aabbs
def encode(shape, gt, f=1.0): gt_map = np.zeros((MapOrdering.NUM_MAPS,) + shape) for aabb in gt: aabb = aabb.scale(f, f) # segmentation map aabb_clip = AABB(0, shape[0] - 1, 0, shape[1] - 1) aabb_word = aabb.scale_around_center(0.5, 0.5).as_type(int).clip(aabb_clip) aabb_sur = aabb.as_type(int).clip(aabb_clip) gt_map[MapOrdering.SEG_SURROUNDING, aabb_sur.ymin:aabb_sur.ymax + 1, aabb_sur.xmin:aabb_sur.xmax + 1] = 1 gt_map[MapOrdering.SEG_SURROUNDING, aabb_word.ymin:aabb_word.ymax + 1, aabb_word.xmin:aabb_word.xmax + 1] = 0 gt_map[MapOrdering.SEG_WORD, aabb_word.ymin:aabb_word.ymax + 1, aabb_word.xmin:aabb_word.xmax + 1] = 1 # geometry map TODO vectorize for x in range(aabb_word.xmin, aabb_word.xmax + 1): for y in range(aabb_word.ymin, aabb_word.ymax + 1): gt_map[MapOrdering.GEO_TOP, y, x] = y - aabb.ymin gt_map[MapOrdering.GEO_BOTTOM, y, x] = aabb.ymax - y gt_map[MapOrdering.GEO_LEFT, y, x] = x - aabb.xmin gt_map[MapOrdering.GEO_RIGHT, y, x] = aabb.xmax - x gt_map[MapOrdering.SEG_BACKGROUND] = np.clip(1 - gt_map[MapOrdering.SEG_WORD] - gt_map[MapOrdering.SEG_SURROUNDING], 0, 1) return gt_map
def __init__(self, category, drawCallback=None): self.category = category self.mobile = category.mobile # is object mobile self.life = category.life # lifetime (seconds) self.collide = category.collide # collision flag self.threshold = category.threshold # variable update frequency # create my graphics object self.graphicsObject = engine.GraphicsObject(category.source, self.mobile, category.image, drawCallback) # find out the size of my graphics object result = self.graphicsObject.getSimData() (self.centerX, self.centerY, self.width, self.height) = result self.posX = 0 # current X position self.posY = 0 # current Y position self.velocityX = 0 # current X velocity self.velocityY = 0 # current Y velocity self.facing = 0 # current facing (degrees) self.turnRate = 0 # degrees / second self.accel = 0 # speed / second self.alive = 1 # flag for staying alive self.uDelay = 0 # update delay self.uTimer = 0 # update timer self.aabb = AABB() self.aabb.computeFor(self) self.removeCallback = None # callback when removed from the world self.handle = 0
def __init__(self): self.color_index = random.randint(color.MIN_COLOR, color.MAX_COLOR) self.aabb = AABB([0.0, 0.0, 0.0], [0.5, 0.5, 0.5]) self.translation_matrix = numpy.identity(4) self.rotation_matrix = numpy.identity(4) self.scaling_matrix = numpy.identity(4) self.selected = False self.name = None
def calculate_aabb(self): bottom_right = None for word in self: if(bottom_right is None): bottom_right = word.aabb.bottom_right else: bottom_right = (max(bottom_right[0], word.aabb.bottom_right[0]), max(bottom_right[1], word.aabb.bottom_right[1])) self.aabb = AABB(self.top_left, bottom_right)
def __init__(self): self.location = [0, 0, 0] self.color_index = random.randint(color.MIN_COLOR, color.MAX_COLOR) self.aabb = AABB([0.0, 0.0, 0.0], [0.5, 0.5, 0.5]) self.translation = numpy.identity(4) self.scalemat = numpy.identity(4) self.selected = False self.scale_mult = 1.0
def __init__(self, name): self.name = name self.aabb = AABB() self.mesh_data = None self.informations = None self.animation_class = None self.default_material = None self.mesh_buffer_object = MeshBufferObject()
def __init__(self): #该节点的颜色序号 self.color_index = random.randint(color.MIN_COLOR, color.MAX_COLOR) #该节点的平移矩阵,决定了该节点在场景中的位置 self.translation_matrix = numpy.identity(4) #该节点的缩放矩阵,决定了该节点的大小 self.scaling_matrix = numpy.identity(4) self.selected = False self.aabb = AABB([0, 0, 0], 1)
def checkSkip(self, sim, newX, newY, newFacing): """check if this displacement skips any space """ if abs(sim.posX - newX) - sim.width > 0 or abs(sim.posY - newY) - sim.height > 0: #print "skipping %s from: (%.2f, %.2f) to: (%.2f, %.2f)" %( sim, sim.posX, sim.posY, newX, newY) # create a bounding box to fit in the skipped area skipBox = AABB() skipBox.computeFor(sim) # calculate skip box values dx = newX - sim.posX dy = newY - sim.posY if dx > 0: xMultiplier = 1 else: xMultiplier = -1 if dy > 0: yMultiplier = 1 else: yMultiplier = -1 if dy == 0: skipWidth = sim.width * xMultiplier skipHeight = 0 elif dx == 0: skipWidth = 0 skipHeight = sim.height * yMultiplier else: ratio = float(abs(dx)) / float(abs(dy)) if ratio > (float(sim.width) / sim.height): skipWidth = sim.width * xMultiplier skipHeight = (sim.width / ratio) * yMultiplier else: skipWidth = (sim.height * ratio) * xMultiplier skipHeight = sim.height * yMultiplier #print "dx %.2f dy %.2f skipWidth %.2f skipHeight %.2f " % (dx, dy, skipWidth, skipHeight) # move the skipBox to the first position skipPosX = sim.posX + skipWidth skipPosY = sim.posY + skipHeight # move the skipbox along the path while 1: skipBox.transform(skipPosX, skipPosY, newFacing) result = self.checkCollideAABB(skipBox, sim, skipPosX, skipPosY, newFacing) if result: return result if abs(newX - skipPosX) <= sim.width and abs( newY - skipPosY) <= sim.height: break skipPosX += skipWidth skipPosY += skipHeight return 0
def __init__(self): # 该节点的颜色序号 self.color_index = random.randint(color.MIN_COLOR, color.MAX_COLOR) # 该节点的平移矩阵 self.translation_matrix = numpy.identity(4) # 该节点的缩放矩阵 self.scaling_matrix = numpy.identity(4) self.aabb = AABB([0.0, 0.0, 0.0], [0.5, 0.5, 0.5]) self.selected = False
def __init__(self): # the color number of this node self.color_index = random.randint(color.MIN_COLOR, color.MAX_COLOR) self.aabb = AABB([0.0, 0.0, 0.0], [0.5, 0.5, 0.5]) # the pingyi matrix of this node, determines the position of the node in scene self.translation_matrix = numpy.identity(4) # the suofang matrix of this node, determines the size of the node self.scaling_matrix = numpy.identity(4) self.selected = False
def __init__(self, center, radius, material): self.center = center self.radius = radius self.material = material box = AABB(empty, empty) flag, box = self.bounding_box(0, 0, box) if not flag: print("No sort key") raise self.min_box = box.minimum
def decode(pred_map, comp_fg=fg_by_threshold(0.5), f=1): idx = comp_fg(pred_map[MapOrdering.SEG_WORD]) pred_map_masked = pred_map[..., idx[0], idx[1]] aabbs = [] for yc, xc, pred in zip(idx[0], idx[1], pred_map_masked.T): t = pred[MapOrdering.GEO_TOP] b = pred[MapOrdering.GEO_BOTTOM] l = pred[MapOrdering.GEO_LEFT] r = pred[MapOrdering.GEO_RIGHT] aabb = AABB(xc - l, xc + r, yc - t, yc + b) aabbs.append(aabb.scale(f, f)) return aabbs
def main(): fpsClock = pygame.time.Clock() pygame.init() displaySurface = pygame.display.set_mode((screenWidth, screenHeight)) pygame.display.set_caption(title) # blue = AABB(Vector2(60, 60), Vector2(140, 60)); # red = AABB(Vector2(300, 180), Vector2(100, 180)); size = screenWidth / 4 box = AABB(Vector2((screenWidth - size) / 2, (screenHeight - size) / 2), Vector2(size, size)) radius = screenWidth / 10 circle = Circle(Vector2(screenWidth - radius * 3, radius * 2), radius) holdingObject = None holdingOffset = Vector2(0, 0) lastMouseState = (False, False, False) gameRunning = True while (gameRunning): for event in pygame.event.get(): if (event.type == QUIT): gameRunning = False lastMouseState, holdingObject, holdingOffset = updateMouse( lastMouseState, holdingObject, holdingOffset, box, circle, minBounds, maxBounds) renderMouse(displaySurface, holdingObject, holdingOffset) maxIter = 1 i = maxIter while (i > 0): i -= 1 collision, normal, overlap = aabbCircleCollision(box, circle) if (collision): print("Collided! Normal: " + str(normal) + "; Smallest overlap: " + str(overlap)) circle.position += normal * overlap else: break render(displaySurface, box, circle) pygame.display.update() fpsClock.tick(fps) pygame.quit() sys.exit()
def test_scale(): scaled_aabb = AABB((0, 0), (20, 30)).scale(0.5) assert(scaled_aabb.bottom_right[0] == 15) assert(scaled_aabb.bottom_right[1] == 22.5) assert(scaled_aabb.top_left[0] == 5) assert(scaled_aabb.top_left[1] == 7.5) scaled_aabb = AABB((-10, -10), (10, 10)).scale(2) assert (scaled_aabb.bottom_right[0] == 20) assert (scaled_aabb.bottom_right[1] == 20) assert (scaled_aabb.top_left[0] == -20) assert (scaled_aabb.top_left[1] == -20) # Edge case: Scaling an AABB by factor 1.0 should not change its dimensions identically_scaled_aabb = AABB((0, 0), (20, 30)).scale(1.0) assert (identically_scaled_aabb.bottom_right[0] == 20) assert (identically_scaled_aabb.bottom_right[1] == 30) assert (identically_scaled_aabb.top_left[0] == 0) assert (identically_scaled_aabb.top_left[1] == 0) with pytest.raises(TypeError): AABB((0, 0), (10, 10)).scale('up')
def __init__(self, x0, x1, z0, z1, k, mat): self.x0 = x0 self.x1 = x1 self.z0 = z0 self.z1 = z1 self.k = k self.material = mat box = AABB(empty, empty) flag, box = self.bounding_box(0, 0, box) if not flag: print("No sort key") raise self.min_box = box.minimum
def __init__(self): super(SnowFigure, self).__init__() self.child_nodes = [Sphere(), Sphere(), Sphere()] self.child_nodes[0].translate(0, -0.6, 0) self.child_nodes[1].translate(0, 0.1, 0) self.child_nodes[1].scaling_matrix = numpy.dot( self.scaling_matrix, scaling([0.8, 0.8, 0.8])) self.child_nodes[2].translate(0, 0.75, 0) self.child_nodes[2].scaling_matrix = numpy.dot( self.scaling_matrix, scaling([0.7, 0.7, 0.7])) for child_node in self.child_nodes: child_node.color_index = color.MIN_COLOR self.aabb = AABB([0.0, 0.0, 0.0], [0.5, 1.1, 0.5])
def __init__(self, **kwargs): self._id = kwargs['_id'] self.infos = kwargs['infos'] self.pathsInfos = kwargs['vertex'] self.matrix = getValue(kwargs, 'matrix') if isIdentity(self.matrix): self.matrix = None self.content = [] self.aabb = AABB() # added by writeContent self.ratio = 1.0 self.newWidth = 1.0 self.newHeight = 1.0
def getAABB(self): aabb = AABB() lastX = 0 lastY = 0 # to acces values with simplepath format (x, y) = range(-2, 0) if self.tag == addNS('path', 'svg'): blocks = Factory().create('path_parser').parse(self.get('d')) for vertex in blocks: for (cmd, values) in vertex: if values is not None: if cmd == 'C': aabb.addBezier((lastX, lastY), values) elif cmd == 'A': aabb.addArc((lastX, lastY), values) else: aabb.addPoint(values[x], values[y]) lastX = values[x] lastY = values[y] elif self.tag in [addNS('rect', 'svg'), addNS('image', 'svg')]: x = float(self.get('x')) y = float(self.get('y')) width = float(self.get('width')) height = float(self.get('height')) aabb.addPoint(x, y) aabb.addPoint(x + width, y + height) elif self.tag == addNS('use', 'svg'): x = float(self.get('x')) y = float(self.get('y')) # the first character of an href is a # imageId = self.get(addNS('href', 'xlink'))[1:] image = self.svg.getImage(imageId) width = float(image.get('width')) height = float(image.get('height')) aabb.addPoint(x, y) aabb.addPoint(x + width, y + height) else: raise Exception("Can't get AABB of a node which is neither a path \ nor a rect.\nnode tag:%s" % self.tag) return aabb
def bounding_box(self, t0, t1, output_box): if len(self.objects) == 0: return False temp_box = AABB() first_box = True for obj in self.objects: if not obj.bounding_box(t0, t1, temp_box): if first_box: output_box = temp_box else: output_box.replace_values(AABB.surrounding_box(output_box, temp_box)) first_box = False return True