def __init__(self, **argd): """x.__init__(...) initializes x; see x.__class__.__doc__ for signature""" super(OpenGLComponent, self).__init__() # get transformation data and convert to vectors self.size = Vector( *argd.get("size", (0,0,0)) ) self.position = Vector( *argd.get("position", (0,0,0)) ) self.rotation = Vector( *argd.get("rotation", (0.0,0.0,0.0)) ) self.scaling = Vector( *argd.get("scaling", (1,1,1) ) ) # for detection of changes self.oldrot = Vector() self.oldpos = Vector() self.oldscaling = Vector() self.transform = Transform() # name (mostly for debugging) self.name = argd.get("name", "nameless") # create clock self.clock = pygame.time.Clock() self.frametime = 0.0 # get display service displayservice = OpenGLDisplay.getDisplayService() # link display_signal to displayservice self.link((self,"display_signal"), displayservice)
def __init__(self, **argd): """x.__init__(...) initializes x; see x.__class__.__doc__ for signature""" super(Container, self).__init__() # get transformation data and convert to vectors self.position = Vector( *argd.get("position", (0,0,0)) ) self.rotation = Vector( *argd.get("rotation", (0.0,0.0,0.0)) ) self.scaling = Vector( *argd.get("scaling", (1,1,1) ) ) # for detection of changes self.oldrot = Vector() self.oldpos = Vector() self.oldscaling = Vector() # inital apply trasformations self.transform = Transform() self.components = [] self.rel_positions = {} self.rel_rotations = {} self.rel_scalings = {} self.poscomms = {} self.rotcomms = {} self.scacomms = {} contents = argd.get("contents", None) if contents is not None: for (comp, params) in contents.items(): self.addElement(comp, **params)
def testRemoveWithDuplicates(self): vec = Vector() vec.append("a") vec.append("b") vec.append("c") self.duplicatesVec.remove("b") self.assertEquals(vec, self.duplicatesVec)
def lanczos(A): k = len(A) b = Vector.rand(n=k) q = [Vector.new(n=k) for i in range(2)] q[1] = b / abs(b) b = [0] a = [0] for i in range(1, int(2 * sqrt(k))): z = Vector((A * q[i]).transpose()[0]) a.append(float(Matrix([q[i]]) * z)) z = z - q[i] * a[i] - q[i-1] * b[i-1] for j in q: z -= j * (z * j) for j in q: z -= j * (z * j) b.append(abs(z)) if b[i] == 0: break q.append(z / b[i]) Q = Matrix(q[-k-1:-1]).transpose() T = Q.transpose() * A * Q return (Q, T, )
def testExtendByEmpty(self): vec = Vector() for i in range(BIG_VEC_SIZE): vec.append(i) self.bigVec.extend(Vector()) self.assertEqual(self.bigVec, vec) self.assertEqual(self.bigVec, self.cleanBigVec)
def collide(self, p1, p2): """Collission detection and handling method""" distance = Vector.distance_between(p1.pos, p2.pos) if distance < (p1.size + p2.size): angle = Vector.angle_between(p1.pos, p2.pos) + 0.5 * math.pi total_mass = p1.mass + p2.mass p1.direction = Vector(p1.direction.length * (p1.mass - p2.mass) / total_mass, p1.direction.angle) \ + Vector(2 * p2.direction.length * p2.mass / total_mass, angle) p2.direction = Vector(p2.direction.length * (p2.mass - p1.mass) / total_mass, p2.direction.angle) \ + Vector(2 * p1.direction.length * p1.mass / total_mass, angle) p1.direction.length *= self.elasticity p2.direction.length *= self.elasticity tangent = Vector.angle_between(p1.pos, p2.pos) # bounce on tangent #p1.direction.bounce(2 * tangent) #p2.direction.bounce(2 * tangent) # change speed #(p1.direction.length, p2.direction.length) = (p2.direction.length, p1.direction.length) #avoid sticky problem angle = 0.5 * math.pi + tangent overlap = 0.5 * (p1.size + p2.size - distance + 1) p1.pos.x += math.sin(angle) + overlap p1.pos.y -= math.cos(angle) + overlap p2.pos.x -= math.sin(angle) + overlap p2.pos.y += math.cos(angle) + overlap
def testInsertAtStartNegative(self): self.bigVec.insert(-BIG_VEC_SIZE, "a") vec = Vector() vec.append("a") for i in range(BIG_VEC_SIZE): vec.append(i) self.assertEqual(self.bigVec, vec)
def resolve(self): """ Return combined result of all steering behaviours. """ acc=Vector(0,0) #if type(self.player.state) == Player.RxAttack: # pdb.set_trace() if self._avoid_defenders_on: acc += self.avoid_defenders() * self.w_avoid_defenders if self._seek_on: acc += self.seek() * self.w_seek if self._seek_end_zone_on: acc += self.seek_end_zone() * self.w_seek_end_zone if self._avoid_walls_on: acc += self.avoid_walls() * self.w_avoid_walls if self._pursue_on: acc += self.pursue() * self.w_pursue if self._block_on: acc += self.block() * self.w_block if self._avoid_friends_on: acc += self.avoid_friends() * self.w_avoid_friends if self._zone_defend_on: acc += self.zone_defend() * self.w_zone_defend if self._guard_on: acc += self.guard() * self.w_guard if self._stay_in_range_on: acc += self.stay_in_range() * self.w_stay_in_range if self._avoid_end_zone_on: acc += self.avoid_end_zone() * self.w_avoid_end_zone if self._arrive_at_speed_on: acc += self.arrive_at_speed() * self.w_arrive_at_speed return acc.truncate(self.player.top_acc)
def testInsertAtEnd(self): self.bigVec.insert(BIG_VEC_SIZE, "a") vec = Vector() for i in range(BIG_VEC_SIZE): vec.append(i) vec.append("a") self.assertEqual(self.bigVec, vec)
def __init__(self, coords=(0, 0), speed=(0, 0)): self.coords = Vector(coords) self.speed = Vector(speed) self.color = (250, 0, 0) self.acsel = Vector((0, 0)) self.status = MOVE self.angle_speed = 0.1
def __init__(self, world, name, image, text): """Base class used to construct a game entity. Returns new GameEntity object with the specified variables world, name,image, text, location, destination, speed, brain and id, this is a super class and should ideally be used via inheritance world: holds a world object. For game entities this should ideally be the world game name: holds the name of the particular entity being constructed e.g. zombie image: holds the location of the image that will be used as the main image for whatever GameEntity is constructed. This image holder will also be used to store the image as a result of rotation for display start_image: holds the location of the image that will be used as the main image for whatever GameEntity is constructed. This one however will not be altered but used as a reference to reset the rotational image when a new rotation is required. text: holds the text that will be displayed in a textual entity; for example the TextBox Entity location: holds a default Vector of (0,0) that will be altered to set the location of the enity that is created destination: holds a default Vector of (0,0) that will be altered to set the destination location of the entity heading: holds a default Vector of (0,0) that will be altered to set the heading; vector between two points with no size. Can be seen as the direction last_heading: holds a default Vector of (0,0), this heading will typically be used to remember the last heading that was used for rotating an entity image, so that rotation does not get caught in an infinite loop speed: holds a number variable default 0. that will be altered to set the speed of the entity that is created brain: holds a StateManager object that is used to manage the states that the entity object will use id: holds the numerial id for the entity object that is being created """ self.world = world self.name = name self.image = image self.start_image = image self.text = text self.location = Vector(0,0) self.destination = Vector(0,0) self.heading = Vector(0,0) self.last_heading = Vector(0,0) self.speed = 0. self.brain = StateManager() self.id = 0
def volume(self): ps = Vector(self.p,self.s) qs = Vector(self.q,self.s) rs = Vector(self.r,self.s) return ps * (qs.cross(rs))/6.0
def testRemoveAtEnd(self): vec = Vector() for i in range(BIG_VEC_SIZE-1): vec.append(i) self.bigVec.remove(BIG_VEC_SIZE-1) self.assertEqual(vec, self.bigVec)
def testExtendGood(self): vec = Vector() for i in range(BIG_VEC_SIZE): vec.append(i) vec.append(10) self.bigVec.extend(self.oneVec) self.assertEqual(self.bigVec, vec)
def testRemoveAtStart(self): vec = Vector() for i in range(1,BIG_VEC_SIZE): vec.append(i) self.bigVec.remove(0) vec.remove(0) self.assertEqual(vec, self.bigVec)
def __init__(self, used, cut): """Create a new 'Rpg' instance """ Vector.__init__(self, used, cut) self.rm_dupli = defaultdict(list) self.head_in_read = [] self.min_size = 1
def __init__(self, ax, ay, bx=0.0, by=0.0): "Start and end are Vectors" if isinstance(ax, Vector) and isinstance(ay, Vector): self.start = ax self.end = ay else: self.start = Vector(ax, ay) self.end = Vector(bx, by)
def __init__(self, coords): self.coords = Vector(coords) self.image = pygame.Surface((50, 40), pygame.SRCALPHA) self.speed = Vector((10, 0)) self.boost = 1 self.direction = self.speed self.state = NORMAL self.draw()
def __init__(self, used, cut, nb_sample, **opt): """Create a new 'Sample' instance """ Vector.__init__(self, used, cut, **opt) self._nb_sample = nb_sample self.vector_val = ''
def testManyRemoves(self): vec = Vector() for i in range(50, BIG_VEC_SIZE): vec.append(i) for i in range(50): self.bigVec.remove(i) self.assertEquals(vec, self.bigVec)
def test_Vector_attribute_setting_should_work(x,y, new_x,new_y): v = Vector(x,y) v.x = new_x assert v.x == new_x assert v.y == y v.y = new_y assert v.y == new_y assert v.x == new_x
def test_length(self): obj = Vector.from_tuple(1, 0, 0) self.assertEqual(obj.length(), 1) obj = Vector.from_tuple(0, 0, 0) self.assertEqual(obj.length(), 0.0) obj = Vector.from_tuple(1, 1, 1) self.assertEqual(obj.length(), math.sqrt(3.0)) self.assertEqual(obj.length_sqrd(), 3.0)
def test_rot_align(self): obj1 = Vector.from_tuple(1, 0, 0) obj2 = Vector.from_tuple(0, 1, 0) transformation = Utils3d.get_rot_align(obj1, obj2) #print transformation result = transformation.mul_vec(obj1) #print result self.assertEqual(result, obj2)
def test_shift(self): """shift vector with transformation matrix""" vector = Vector.from_tuple(1, 0, 0) # this should shift X Axis about 2 shift_vector = Utils3d.get_shift_vector(2, 0, 0) # calculate linear transformation A*v t = shift_vector + vector # result should be shifted about 2 on x-axis self.assertEqual(t, Vector.from_tuple(3, 0, 0))
def testludecomp(self): # TODO: Fix this test and the function under test! return A = Matrix([1, 2, 3], [4, 5, 6], [7, 8, 9]) m2 = A.clone() (index, d) = m2.ludecomp() b = Vector(6, -1, 3) x = m2.lubacksub(index, b.clone()) assert(False)
def testInsertMiddle(self): vec1 = Vector() vec1.append("a") vec1.append("b") vec1.append("c") vec2 = Vector() vec2.append("a") vec2.append("c") vec2.insert(1,"b") self.assertEqual(vec1, vec2)
def distFromPointToLine(p, p1, p2): line = Vector(p2) - Vector(p1) toP = Vector(p) - Vector(p1) dot = toP.dot(line) if 0 <= dot <= line.length ** 2: projection = toP.proj(line) rejection = toP - projection return rejection.length else: return min(toP.length, (Vector(p) - Vector(p2)).length)
def rule3(self, hoik): v = Vector(0, 0) if hoik.pos.x < 10: v.x = 20 elif hoik.pos.x > C.SCREEN_SIZE.x-10: v.x = -20 if hoik.pos.y < 10: v.y = 20 elif hoik.pos.y > C.SCREEN_SIZE.y-10: v.y = -20 return v
def test_linearIndependenceWorks(self): one_1 = Vector([1, 1]) three_3 = Vector([3, 3]) self.assertFalse(Vector.areLinearlyIndependent([one_1, three_3])) one = Vector([1]) three = Vector([3]) self.assertFalse(Vector.areLinearlyIndependent([one, three])) one_3 = Vector([1, 3]) self.assertTrue(Vector.areLinearlyIndependent([one_1, one_3]))
def __init__(self, pos = [130,0],vmax = 60., thePath=[]): self.currentNode = 0 self.pathDir = 1 self.nodes = thePath.getNodes() self.t = self.nodes[self.currentNode] self.max_v = vmax self.p = Vector(pos) self.v = Vector([0., 0.]) self.max_see_ahead = 30 self.max_avoid_force = 1.5 self.obstacles = []
def generateSceneNode(file_name, xz_size, peak_height, base_height, blur_iterations, max_size, lighter_is_higher, file): scene_node = SceneNode() mesh = MeshBuilder() #初始化 # img = QImage(file_name) im = Image.open(file_name) # if im.isNull(): # Logger.log("e", "Image is corrupt.") # return None # width = max(img.width(), 2) # height = max(img.height(), 2) width = max(im.size[0], 2) height = max(im.size[1], 2) aspect = height / width # if im.width() < 2 or im.height() < 2: # img = img.scaled(width, height, Qt.IgnoreAspectRatio) # im = im.resize(width, height, Image.ANTIALIAS) base_height = max(base_height, 0) peak_height = max(peak_height, -base_height) xz_size = max(xz_size, blur_iterations) scale_vector = Vector(xz_size, peak_height, xz_size) if width > height: scale_vector = scale_vector.set(z=scale_vector.z * aspect) elif height > width: scale_vector = scale_vector.set(x=scale_vector.x / aspect) if width > max_size or height > max_size: scale_factor = max_size / width if height > width: scale_factor = max_size / height width = int(max(round(width * scale_factor), 2)) height = int(max(round(height * scale_factor), 2)) # img = img.scaled(width, height, Qt.IgnoreAspectRatio) im = im.resize((width, height), Image.ANTIALIAS) width_minus_one = width - 1 height_minus_one = height - 1 #Job.yieldThread() texel_width = 1.0 / (width_minus_one) * scale_vector.x texel_height = 1.0 / (height_minus_one) * scale_vector.z height_data = numpy.zeros((height, width), dtype=numpy.float32) for x in range(0, width): for y in range(0, height): # qrgb = img.pixel(x, y) qrgb = im.getpixel((x, y)) R = qrgb[0] G = qrgb[1] B = qrgb[2] avg = float(R + G + B) / (3 * 255) # qR=qRed(qrgb) # qG=qGreen(qrgb) # qB=qBlue(qrgb) # avg=float(qR+qG+qB)/(3 * 255) # avg = float(qRed(qrgb) + qGreen(qrgb) + qBlue(qrgb)) / (3 * 255) height_data[y, x] = avg #Job.yieldThread() if not lighter_is_higher: height_data = 1 - height_data for _ in range(0, blur_iterations): copy = numpy.pad(height_data, ((1, 1), (1, 1)), mode="edge") height_data += copy[1:-1, 2:] height_data += copy[1:-1, :-2] height_data += copy[2:, 1:-1] height_data += copy[:-2, 1:-1] height_data += copy[2:, 2:] height_data += copy[:-2, 2:] height_data += copy[2:, :-2] height_data += copy[:-2, :-2] height_data /= 9 # Job.yieldThread() height_data *= scale_vector.y height_data += base_height heightmap_face_count = 2 * height_minus_one * width_minus_one total_face_count = heightmap_face_count + (width_minus_one * 2) * (height_minus_one * 2) + 2 mesh.reserveFaceCount(total_face_count) # initialize to texel space vertex offsets. # 6 is for 6 vertices for each texel quad. heightmap_vertices = numpy.zeros( (width_minus_one * height_minus_one, 6, 3), dtype=numpy.float32) heightmap_vertices = heightmap_vertices + numpy.array( [[[0, base_height, 0], [0, base_height, texel_height], [texel_width, base_height, texel_height], [texel_width, base_height, texel_height], [texel_width, base_height, 0], [0, base_height, 0]]], dtype=numpy.float32) offsetsz, offsetsx = numpy.mgrid[0:height_minus_one, 0:width - 1] offsetsx = numpy.array(offsetsx, numpy.float32).reshape(-1, 1) * texel_width offsetsz = numpy.array(offsetsz, numpy.float32).reshape(-1, 1) * texel_height # offsets for each texel quad heightmap_vertex_offsets = numpy.concatenate([ offsetsx, numpy.zeros((offsetsx.shape[0], offsetsx.shape[1]), dtype=numpy.float32), offsetsz ], 1) heightmap_vertices += heightmap_vertex_offsets.repeat(6, 0).reshape(-1, 6, 3) # apply height data to y values heightmap_vertices[:, 0, 1] = heightmap_vertices[:, 5, 1] = height_data[:-1, : -1].reshape(-1) heightmap_vertices[:, 1, 1] = height_data[1:, :-1].reshape(-1) heightmap_vertices[:, 2, 1] = heightmap_vertices[:, 3, 1] = height_data[1:, 1:].reshape(-1) heightmap_vertices[:, 4, 1] = height_data[:-1, 1:].reshape(-1) heightmap_indices = numpy.array(numpy.mgrid[0:heightmap_face_count * 3], dtype=numpy.int32).reshape(-1, 3) mesh._vertices[0:(heightmap_vertices.size // 3), :] = heightmap_vertices.reshape(-1, 3) mesh._indices[0:(heightmap_indices.size // 3), :] = heightmap_indices mesh._vertex_count = heightmap_vertices.size // 3 mesh._face_count = heightmap_indices.size // 3 geo_width = width_minus_one * texel_width geo_height = height_minus_one * texel_height # bottom mesh.addFaceByPoints(0, 0, 0, 0, 0, geo_height, geo_width, 0, geo_height) mesh.addFaceByPoints(geo_width, 0, geo_height, geo_width, 0, 0, 0, 0, 0) # north and south walls for n in range(0, width_minus_one): x = n * texel_width nx = (n + 1) * texel_width hn0 = height_data[0, n] hn1 = height_data[0, n + 1] hs0 = height_data[height_minus_one, n] hs1 = height_data[height_minus_one, n + 1] mesh.addFaceByPoints(x, 0, 0, nx, 0, 0, nx, hn1, 0) mesh.addFaceByPoints(nx, hn1, 0, x, hn0, 0, x, 0, 0) mesh.addFaceByPoints(x, 0, geo_height, nx, 0, geo_height, nx, hs1, geo_height) mesh.addFaceByPoints(nx, hs1, geo_height, x, hs0, geo_height, x, 0, geo_height) # west and east walls for n in range(0, height_minus_one): y = n * texel_height ny = (n + 1) * texel_height hw0 = height_data[n, 0] hw1 = height_data[n + 1, 0] he0 = height_data[n, width_minus_one] he1 = height_data[n + 1, width_minus_one] mesh.addFaceByPoints(0, 0, y, 0, 0, ny, 0, hw1, ny) mesh.addFaceByPoints(0, hw1, ny, 0, hw0, y, 0, 0, y) mesh.addFaceByPoints(geo_width, 0, y, geo_width, 0, ny, geo_width, he1, ny) mesh.addFaceByPoints(geo_width, he1, ny, geo_width, he0, y, geo_width, 0, y) mesh.calculateNormals(fast=True) scene_node.setMeshData(mesh.build()) saveScene(file, scene_node)
class VectorTest(unittest.TestCase): def setUp(self): p1 = Point() p2 = Point(1, 1, 1) p3 = Point(-1, -1, 1) self.v1 = Vector(p1, p2) self.v2 = Vector(p1, p3) def tearDown(self): self.v1 = None self.v2 = None def test_value(self): true = self.assertTrue true(self.v1.value, [1, 1, 1]) true(self.v2.value, [-1, -1, 1]) def test_length(self): true = self.assertTrue l1 = self.v1.length l2 = self.v2.length true(l1, 3**0.5) true(l2, l1) def test_direction(self): true = self.assertTrue d1 = self.v1.direction d2 = self.v2.direction ansv = 3**0.5 ans1 = Vector(Point(), Point(ansv, ansv, ansv)) ans2 = Vector(Point(), Point(-ansv, -ansv, ansv)) true(d1.value, ans1.value) true(d2.value, ans2.value) def test_normalize(self): true = self.assertTrue self.v1.normalize self.v2.normalize ansv = 3**0.5 ans1 = Vector(Point(), Point(ansv, ansv, ansv)) ans2 = Vector(Point(), Point(-ansv, -ansv, ansv)) true(self.v1.value, ans1.value) true(self.v2.value, ans2.value) def test_dot(self): true = self.assertTrue dot1 = self.v1.dot(self.v2) dot2 = self.v2.dot(self.v1) true(dot1, 1) true(dot1, dot2) def test_cross(self): true = self.assertTrue cross1 = self.v1.cross(self.v2) cross2 = self.v2.cross(self.v1) ans1 = Vector(Point(), Point(2, -2, 0)) ans2 = Vector(Point(), Point(-2, 2, 0)) true(cross1, ans1.value) true(cross2, ans2.value) def test_rotation(self): deg = self.v1.rotation(self.v2) self.assertTrue(deg, 70.52877936550934) def test_add(self): v = self.v1 + self.v2 self.assertTrue(v.value, [0, 0, 2]) def test_sub(self): v = self.v1 - self.v2 self.assertTrue(v.value, [2, 2, 0]) def test_mul(self): true = self.assertTrue v3 = self.v1 * 2 v4 = self.v2 * -2 true(v3.value, [2, 2, 2]) true(v4.value, [2, 2, -2]) def test_div(self): true = self.assertTrue v3 = self.v1 / 0.5 v4 = self.v2 / -0.5 true(v3.value, [2, 2, 2]) true(v4.value, [2, 2, -2]) def test_iadd(self): self.v1 += self.v2 self.assertTrue(self.v1, [0, 0, 2]) def test_isub(self): self.v1 -= self.v2 self.assertTrue(self.v1, [2, 2, 0]) def test_imul(self): true = self.assertTrue self.v1 *= 2 self.v2 *= -2 true(self.v1.value, [2, 2, 2]) true(self.v2.value, [2, 2, -2]) def test_idiv(self): true = self.assertTrue self.v1 /= 0.5 self.v2 /= -0.5 true(self.v1.value, [2, 2, 2]) true(self.v2.value, [2, 2, -2])
def test_repr(): assert repr(Vector(1,2)) == "Vector(1, 2)"
def to_vector(vector): return Vector(vector)
def _get_axial_vector(self, pos_type): return Vector(getattr(self.node1, pos_type), getattr(self.node2, pos_type))
class EigenStuff: def __init__(self, canvas, master, evRow, probRow, color, num, ebWidth): self.canvas = canvas['canvas'] self.cDiag = canvas['diagonal'] self.color = color self.evLabel = Label(master, text='', fg=color, width=20) self.evLabel.grid(row=evRow, columnspan=2) self.probLabel = Label(master, text='', fg=color, width=20) self.probLabel.grid(row=probRow, columnspan=2) self.ev = self.canvas.create_line(0,0,0,0,fill=color, dash=[10,15], tag='eigen') self.projEv = self.canvas.create_line(0,0,0,0, fill='cyan', arrow='last', width=1, tag='proj') self.projEvDash = self.canvas.create_line(0,0,0,0, fill='cyan', dash=[10,5], width=1, tag='proj') self.eb = Vector(canvas, master, None, color, ebWidth, 'eigen') self.num = num #for labels self.vals = None def setEvLabel(self, eigenVal): if eigenVal.imag == 0: self.evLabel['text'] = "λ" + str(self.num) + " = " + str(round(eigenVal.real, 2)) else: self.evLabel['text'] = "λ" + str(self.num) + " = " + str( round(eigenVal.real, 2)) + ' + ' + str(round(eigenVal.imag, 2)) + 'i' def setProbLabel(self, prob): self.probLabel['text'] = 'P' + str(self.num) + ' = ' + str(round(prob, 2)) def setVals(self, evs): self.vals = evs self.eb.setVals(evs) def drawLine(self, unitSize): cWidth = int(self.canvas['width']) cHeight = int(self.canvas['height']) x1, y1 = (-self.cDiag * self.vals).vals() x2, y2 = (self.cDiag * self.vals).vals() self.canvas.coords(self.ev, cWidth/2 + x1*unitSize, cHeight/2 - y1*unitSize, cWidth/2 + x2*unitSize, cHeight/2 - y2*unitSize) def setEvLabelBackground(self, color): self.evLabel['bg'] = color def probView(self, view): if view: self.probLabel.grid() else: self.probLabel.grid_remove() def drawProjections(self, x2, y2, amp, unitSize): cWidth = int(self.canvas['width']) cHeight = int(self.canvas['height']) x, y = (amp * self.vals).vals() self.canvas.coords(self.projEv, cWidth/2, cHeight/2, cWidth/2 + x*unitSize, cHeight/2 + -y*unitSize ) self.canvas.coords(self.projEvDash, cWidth/2+x*unitSize, cHeight/2 + -y*unitSize, cWidth/2 + x2*unitSize, cHeight/2 + -y2*unitSize ) def drawEigenBasis(self, unitSize): self.eb.drawVector(unitSize) def setComplexMode(self, complexMode): self.eb.setComplexMode(complexMode) self.canvas.coords(self.ev, 0, 0, 0, 0)
class OpenGLComponent(Axon.AdaptiveCommsComponent.AdaptiveCommsComponent): """\ OpenGLComponent(...) -> create a new OpenGL component (not very useful though; it is rather designed to inherit from). This components implements the interaction with the OpenGLDisplay service that is needed to setup, draw and move an object using OpenGL. Keyword arguments: - size -- three dimensional size of component (default=(0,0,0)) - rotation -- rotation of component around (x,y,z) axis (defaul=(0,0,0)) - scaling -- scaling along the (x,y,z) axis (default=(1,1,1)) - position -- three dimensional position (default=(0,0,0)) - name -- name of component (mostly for debugging, default="nameless") """ Inboxes = { "inbox": "not used", "control": "For shutdown messages", "callback": "for the response after a displayrequest", "events": "Input events", "position" : "receive position triple (x,y,z)", "rotation": "receive rotation triple (x,y,z)", "scaling": "receive scaling triple (x,y,z)", "rel_position" : "receive position triple (x,y,z)", "rel_rotation": "receive rotation triple (x,y,z)", "rel_scaling": "receive scaling triple (x,y,z)", } Outboxes = { "outbox": "not used", "signal": "For shutdown messages", "display_signal" : "Outbox used for communicating to the display surface", "position" : "send position status when updated", "rotation": "send rotation status when updated", "scaling": "send scaling status when updated", } def __init__(self, **argd): """x.__init__(...) initializes x; see x.__class__.__doc__ for signature""" super(OpenGLComponent, self).__init__() # get transformation data and convert to vectors self.size = Vector( *argd.get("size", (0,0,0)) ) self.position = Vector( *argd.get("position", (0,0,0)) ) self.rotation = Vector( *argd.get("rotation", (0.0,0.0,0.0)) ) self.scaling = Vector( *argd.get("scaling", (1,1,1) ) ) # for detection of changes self.oldrot = Vector() self.oldpos = Vector() self.oldscaling = Vector() self.transform = Transform() # name (mostly for debugging) self.name = argd.get("name", "nameless") # create clock self.clock = pygame.time.Clock() self.frametime = 0.0 # get display service displayservice = OpenGLDisplay.getDisplayService() # link display_signal to displayservice self.link((self,"display_signal"), displayservice) def main(self): # create display request self.disprequest = { "OGL_DISPLAYREQUEST" : True, "objectid" : id(self), "callback" : (self,"callback"), "events" : (self, "events"), "size": self.size } # send display request self.send(self.disprequest, "display_signal") # inital apply trasformations self.applyTransforms() # setup function from derived objects self.setup() # initial draw to display list self.redraw() # wait for response on displayrequest while not self.dataReady("callback"): yield 1 self.identifier = self.recv("callback") while 1: yield 1 while self.dataReady("control"): cmsg = self.recv("control") # if isinstance(cmsg, producerFinished) or isinstance(cmsg, shutdownMicroprocess): # self.send(cmsg, "signal") # return self.frametime = float(self.clock.tick())/1000.0 self.handleMovement() self.handleEvents() self.applyTransforms() # frame function from derived objects self.frame() def applyTransforms(self): """ Use the objects translation/rotation/scaling values to generate a new transformation Matrix if changes have happened. """ # generate new transformation matrix if needed if self.oldscaling != self.scaling or self.oldrot != self.rotation or self.oldpos != self.position: self.transform = Transform() self.transform.applyScaling(self.scaling) self.transform.applyRotation(self.rotation) self.transform.applyTranslation(self.position) if self.oldscaling != self.scaling: self.send(self.scaling.toTuple(), "scaling") self.oldscaling = self.scaling.copy() if self.oldrot != self.rotation: self.send(self.rotation.toTuple(), "rotation") self.oldrot = self.rotation.copy() if self.oldpos != self.position: self.send(self.position.toTuple(), "position") self.oldpos = self.position.copy() # send new transform to display service transform_update = { "TRANSFORM_UPDATE": True, "objectid": id(self), "transform": self.transform } self.send(transform_update, "display_signal") def handleMovement(self): """ Handle movement commands received by corresponding inboxes. """ while self.dataReady("position"): pos = self.recv("position") self.position = Vector(*pos) while self.dataReady("rotation"): rot = self.recv("rotation") self.rotation = Vector(*rot) while self.dataReady("scaling"): scaling = self.recv("scaling") self.scaling = Vector(*scaling) while self.dataReady("rel_position"): self.position += Vector(*self.recv("rel_position")) while self.dataReady("rel_rotation"): self.rotation += Vector(*self.recv("rel_rotation")) while self.dataReady("rel_scaling"): self.scaling = Vector(*self.recv("rel_scaling")) ## # Methods to be used by derived objects ## def addListenEvents(self, events): """\ Sends listening request for pygame events to the display service. The events parameter is expected to be a list of pygame event constants. """ for event in events: self.send({"ADDLISTENEVENT":event, "objectid":id(self)}, "display_signal") def removeListenEvents(self, events): """\ Sends stop listening request for pygame events to the display service. The events parameter is expected to be a list of pygame event constants. """ for event in events: self.send({"REMOVELISTENEVENT":event, "objectid":id(self)}, "display_signal") def redraw(self): """\ Invoke draw() and save its commands to a newly generated displaylist. The displaylist name is then sent to the display service via a "DISPLAYLIST_UPDATE" request. """ # display list id displaylist = glGenLists(1); # draw object to its displaylist glNewList(displaylist, GL_COMPILE) self.draw() glEndList() dl_update = { "DISPLAYLIST_UPDATE": True, "objectid": id(self), "displaylist": displaylist } self.send(dl_update, "display_signal") ## # Method stubs to be overridden by derived objects ## def handleEvents(self): """ Method stub Override this method to do event handling inside. Should look like this:: while self.dataReady("events"): event = self.recv("events") # handle event ... """ pass def draw(self): """ Method stub Override this method for drawing. Only use commands which are needed for drawing. Will not draw directly but be saved to a displaylist. Therefore, make sure not to use any commands which cannot be stored in displaylists (unlikely anyway). """ pass def setup(self): """ Method stub Override this method for component setup. It will be called on the first scheduling of the component. """ pass def frame(self): """ Method stub Override this method for operations you want to do every frame. It will be called every time the component is scheduled. Do not include infinite loops, the method has to return every time it gets called. """ pass
try: import simplegui except: import SimpleGUICS2Pygame.simpleguics2pygame as simplegui from Vector import Vector from LineMove import LineMove myLine = LineMove((Vector(0, 0)), (Vector(600, 0))) myLine2 = LineMove((Vector(0, 0)), (Vector(700, 0))) frame = simplegui.create_frame("Half-Life 3", 500, 500) frame.set_draw_handler(myLine.update) frame.start()
def handleEvents(self): while self.dataReady("events"): event = self.recv("events") if event.type == pygame.MOUSEBUTTONDOWN and self.identifier in event.hitobjects: self.rotation += Vector(0,0,10) self.rotation %= 360
def __init__(self, center_x, center_y, restitution): self.center = Vector(center_x, center_y) self.restitution = restitution self.velocity = Vector(0, 0) self.acceleration = Vector(0, 0) self.collision_mask = (Body, )
def sum_vector(vector1, vector2): return Vector(vector1.psi + vector2.psi)
#!/usr/bin/env python import sys from Vector import Vector V1 = Vector(1, 1) V2 = Vector(2, 2) try: V3 = V1 + V2 except TypeError: print "Add Test failed! Not defined" try: assert (V3.getX() == 3 and V3.getY() == 3) print "Add Test succeeded!" except AssertionError: print "Add Test failed!" try: V3 = V1 - V2 except TypeError: print "Subtraction Test failed! Not defined" try: assert (V3.getX() == -1 and V3.getY() == -1) print "Subtraction Test succeeded!" except AssertionError: print "Subtraction Test failed!"
def updateAcceleration(self): if self.inAir and not self.jumping: self.gravity = Vector(0, 3) else: self.gravity = Vector(0, 0)
def Euler(x, y, z): # Z-->X-->Y rotX = Quaternion.AxisAngle(Vector(1, 0, 0), x) rotY = Quaternion.AxisAngle(Vector(0, 1, 0), y) rotZ = Quaternion.AxisAngle(Vector(0, 0, 1), z) return rotY * rotX * rotZ
class Player(Sprite): def __init__(self, image, image_alternate, columns, rows): super().__init__(image, image_alternate, columns, rows) pygame.mixer.pre_init( 44100, -16, 1, 512 ) # Prevents Pygame sound delay: https://www.reddit.com/r/pygame/comments/8gsoue/delayed_audio_in_pygame/ self.lives = 2 self.moving = False self.dead = False self.shooting = False self.jumping = False #self.rolling = False self.invincible = False self.bullets = [] self.velocity = Vector(0, 0) self.pos = Vector(SCREENWIDTH / 2, SCREENHEIGHT - 20) self.gravity = Vector(0, 0) self.frameCounter = 0 self.deadCounter = 0 self.inAir = False # Sound effects for the player __location__ = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) soundeffect = os.path.join(__location__, 'Sounds/classic_hurt.ogg') self.oof = simplegui._load_local_sound(soundeffect) __location__ = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) soundeffect = os.path.join(__location__, 'Sounds/gunSound.ogg') self.pew = simplegui._load_local_sound(soundeffect) self.pew.set_volume(.25) def update(self): if self.frameCounter % 10 == 0: self.updateFrame() self.updateVel() self.updateAcceleration() self.pos += self.velocity # Checks to stop player going off the screen if self.pos.getP()[1] > SCREENHEIGHT - 100: self.pos = Vector(self.pos.getP()[0], 620) elif self.pos.getP()[1] < 0: self.pos = Vector(self.pos.getP()[0], 1) self.jumping = False if self.pos.getP()[0] > SCREENWIDTH - 25: self.pos = Vector(1255, self.pos.getP()[1]) elif self.pos.getP()[0] < 25: self.pos = Vector(25, self.pos.getP()[1]) self.frameCounter += 1 # Custom draw method for the player sprite as the sprite sheet is more complex and had some issues def draw(self, canvas): if self.right: centreDest = (self.pos.getP()[0], self.pos.getP()[1]) centerSource = [ self.frameSize[i] * self.currentFrame[i] + self.frameCentre[i] for i in [0, 1] ] canvas.draw_image(self.image, centerSource, self.frameSize, centreDest, self.sizeDest) else: centreDest = (self.pos.getP()[0], self.pos.getP()[1]) centerSource = [ (self.width - (self.frameSize[0] * self.currentFrame[0] + self.frameCentre[0])), (self.frameSize[1] * self.currentFrame[1] + self.frameCentre[1]) ] canvas.draw_image(self.alternateimage, centerSource, self.frameSize, centreDest, self.sizeDest) # Updating the frame depending on the animation def updateFrame(self): self.currentFrame[0] += 1 # Death animation if self.lives <= 0: self.deadCounter += 1 self.currentFrame[1] = 8 if self.currentFrame[0] > 5: self.dead = True # Rolling Animation (Not used in final game) #elif self.rolling: # self.currentFrame[1] = 7 # # Run rolling animation # if self.currentFrame[0] >= 4: # self.currentFrame[0] = 0 # self.rolling = False # Jumping while not shooting elif self.jumping and not self.shooting: self.currentFrame[1] = 5 if self.currentFrame[0] >= 6: self.currentFrame[0] = 4 # Shooting while still elif self.shooting and not self.moving: self.currentFrame[1] = 2 if self.currentFrame[0] >= 8: self.currentFrame[0] = 0 # Shooting while moving elif self.moving and self.shooting: self.currentFrame[1] = 4 if self.currentFrame[0] >= 8: self.currentFrame[0] = 0 # Moving while not shooting elif self.moving and not self.shooting: self.currentFrame[1] = 3 if self.currentFrame[0] >= 8: self.currentFrame[0] = 0 # Doing nothing else: self.currentFrame[1] = 1 if self.currentFrame[0] >= 8: self.currentFrame[0] = 0 # Updating the velocity def updateVel(self): if self.moving: # Change horizontal velocity if self.right: self.velocity = Vector(5, self.velocity.getP()[1]) else: self.velocity = Vector(-5, self.velocity.getP()[1]) self.velocity = Vector(self.velocity.getP()[0] * 0.94, self.velocity.getP()[1]) self.velocity += self.gravity if self.jumping: self.velocity = Vector(self.velocity.getP()[0], -10) # Updating the acceleration def updateAcceleration(self): if self.inAir and not self.jumping: self.gravity = Vector(0, 3) else: self.gravity = Vector(0, 0) # Spawns a non hostile bullet def shoot(self): self.pew.play() xStart, yStart = self.pos.getP() __location__ = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) imagenormal = os.path.join(__location__, 'images/sprites/boomerangbullet.png') imagealternate = os.path.join( __location__, 'images/sprites/boomerangbulletleft.png') # Sets velocity of bullet repective to direction the player is facing if self.right: vel = Vector(6, 0) right = True xStart += 60 else: vel = Vector(-6, 0) right = False xStart -= 60 startPos = Vector(xStart, yStart + 30) return Bullet(startPos, vel, False, "bullet", right, imagenormal, imagealternate, 8, 1) # Following methods to be called in interaction class after user inputs to switch boolean variables def startMoving(self): if self.lives > 0: self.moving = True def startShooting(self): if self.lives > 0: self.shooting = True self.bullets.append(self.shoot()) self.currentFrame[0] = 2 #def startRoll(self): # if self.lives > 0: # self.rolling = True def startJump(self): if self.lives > 0: self.jumping = True self.inAir = True # Called from interaction class when user input ends def stopJump(self): if self.lives > 0: self.jumping = False def stopMoving(self): if self.lives > 0: self.moving = False def stopShooting(self): if self.lives > 0: self.shooting = False # Called from interaction class following collision def removeLife(self): if not self.invincible and self.lives > 0: self.lives -= 1 self.oof.set_volume(1) self.oof.play() if self.lives == 0: self.currentFrame[0] = 0
from matrix import Matrix from Vector import Vector # m0 = Matrix((2, 3)) # m1 = Matrix([[1,3,4],[5,6,7]]) # m2 = Matrix([[1,3,4],[5,6,7]], (2, 3)) # A=Matrix([[1,4,-2],[3,5,-6]]) # B=Matrix([[5,2,8,-1], [3,6,4,5], [-2,9,7,-3]]) # C = A * B # print(C.data) A=Matrix([[1, -1,2], [0, -3, 1]]) B=Vector([2,1,0]) C = B*A print(C.values)
''' Created on Nov 21, 2016 @author: iaskarov ''' from Vector import Vector from VectorOperations import vadd, vsubtract, vcomponent, vdot, vangle, pythagorean, sohcahtoa, vcross, is_vparallel, vprojection, is_vorthogonal, vscalar_product if __name__ == '__main__': v1 = Vector([1.5, 9.547, 3.691]) v2 = Vector([-6.007, 0.124, 5.772]) cross = vcross(v1.coordinates, v2.coordinates) print cross.magnitude / 2
def close(enemy, moving_point): p = Vector(moving_point[0][0], moving_point[0][1]) - enemy.position return abs(p.x) < Constants.CONTOUR_EPS and abs( p.y) < Constants.CONTOUR_EPS
def calculateEstPosition(self, lastTransmittedSample, currentTime): deltaTime = currentTime - lastTransmittedSample.sample.time deltaTimeVector = Vector(deltaTime, deltaTime, deltaTime) deltaPosition = lastTransmittedSample.velocity * deltaTimeVector estimatedPosition = lastTransmittedSample.sample.position + deltaPosition return estimatedPosition
def test_addition(): v1 = Vector(1,2) v2 = Vector(1,2) v3 = v1 + v2 assert v3.x == 2 assert v3.y == 4
def GeneratingOneImage(particle_center_x, particle_center_y, R, rho, nm, nP, pol_X, pol_Y, pol_Z, pol_Vx, pol_Vy, pol_Vz, resolution, lens_size, scattering_number_of_iterations): """ This method generates an image based on the rays propagated from the light source, refracted through a particle, and towards a camera lens. :param particle_center_x: Particle center x coordinate. :param particle_center_y: Particle center y coordinate. :param R: Particle radius [m]. :param rho: Ray density per square meter. :param nm: Refractive index of the medium before ray impact. :param nP: Refractive index of the medium after ray impact. :param pol_X: Polarization :param pol_Y: Polarization :param pol_Z: Polarization :param pol_Vx: Polarization :param pol_Vy: Polarization :param pol_Vz: Polarization :param resolution: Resolution of the generated image. Assuming quadratic image. :param lens_size: Camera lens size [m], assuming quadratic lens. :param scattering_number_of_iterations: # Maximum number of iterations the rays are scattered within the particle. :return: The particle captures by the camera as an image. """ # Produce one image. c = Point(0, 0, 0) bead = ParticleSpherical(c, R, nm, nP) pixels = np.zeros(resolution * resolution) # Coordinates for the rays hitting the sphere x, y = GeneratingCoordinates(rho, R, 0, 0) number_of_rays = np.size(x) P = np.ones(number_of_rays) # Power[W] z = np.zeros(number_of_rays) Vx = np.zeros(number_of_rays) Vy = np.zeros(number_of_rays) Vz = np.ones(number_of_rays) v = Vector(x * R, y * R, z, Vx, Vy, Vz) pol = Vector(pol_X, pol_Y, pol_Z, pol_Vx, pol_Vy, pol_Vz) pol = v.mtimes(pol) pol = pol.versor() r = Ray(v, P, pol) s = bead.scattering(r=r, N=scattering_number_of_iterations) plane_normal = np.array([0, 0, 1]) # Define lens plane plane_point = np.array([0, 0, 1]) # Any point on the plane exiting_rays = s[-1]["t"] ray_power = exiting_rays.P for i in range(0, np.size(exiting_rays.v.Vx) - 1): ray_direction = np.array( [exiting_rays.v.Vx[i], exiting_rays.v.Vy[i], exiting_rays.v.Vz[i]]) ray_point = np.array([ exiting_rays.v.X[i], exiting_rays.v.Y[i], exiting_rays.v.Z[i] ]) + np.array([particle_center_x, particle_center_y, 0]) psi = LinePlaneCollision(plane_normal, plane_point, ray_direction, ray_point, lens_size) if psi is not None: # Ray hits the camera lens x_pixel = np.round( (psi[0] + lens_size / 2) / lens_size * (resolution - 1)) y_pixel = np.round( (psi[1] + lens_size / 2) / lens_size * resolution) pixel_index = y_pixel * resolution + x_pixel pixels[int(pixel_index)] = pixels[int(pixel_index)] + ray_power[i] # Normalize the sphere-rays if max(pixels) > 0: pixels = pixels / max(pixels) return np.reshape(pixels, (resolution, resolution))
def test_create_instance_with_defaults(): v1 = Vector() assert v1.x == 0 assert v1.y == 0
def test_coodinate_conversion(): #Testing quadrant 1 coordinate conversion vec = Vector(vector=(1, 1)) guiCoord = vec.getGUIVector1() assert guiCoord[0] == 261 assert guiCoord[1] == 259 #Testing quadrant 2 coordinate conversion vec = Vector(vector=(-3, 10)) guiCoord = vec.getGUIVector1() assert guiCoord[0] == 257 assert guiCoord[1] == 250 #Testing quadrant 3 coordinate conversion vec = Vector(vector=(-5, -10)) guiCoord = vec.getGUIVector1() assert guiCoord[0] == 255 assert guiCoord[1] == 270 #Testing quadrant 4 coordinate conversion vec = Vector(vector=(5, -10)) guiCoord = vec.getGUIVector1() assert guiCoord[0] == 265 assert guiCoord[1] == 270
def test_abs(): v1 = Vector(3,4) assert abs(v1) == 5
def generate_new_enemys(enemys): for i in range(len(enemys), Constants.ENEMYS_NUM): enemys.append( Enemy(enemy_points[random.randint(0, len(enemy_points) - 1)])) return enemys video_capture = cv2.VideoCapture(0) ret, average_frame = video_capture.read() average_frame = cv2.cvtColor(average_frame, cv2.COLOR_BGR2GRAY) moving_provider = MovingProvider(average_frame) HEIGTH, WIDTH = average_frame.shape CENTER = Vector(WIDTH // 2, HEIGTH // 2) base = Base(CENTER, CENTER, WIDTH // 2, HEIGTH // 2) enemy_points = [ Vector(0, 0), Vector(0, HEIGTH), Vector(WIDTH, 0), Vector(WIDTH, HEIGTH) ] enemys = [] for i in range(Constants.ENEMYS_NUM): enemys.append(Enemy(enemy_points[random.randint(0, len(enemy_points) - 1)])) while True: # Capture frame-by-frame
def generate(self, max_rooms, random_percentage, screen_size): """ Generates a list of rooms with a size of `max_rooms` Keyword arguments: max_rooms - an integer with the maximum number of rooms wanted random_percentage - the percent of rooms to keep for adding randomly to the map screen_size - a tuple of ints that represent the screen size """ self.__rooms = [] linear_rooms = int((max_rooms + 1) * (1 - random_percentage)) random_rooms = max_rooms - linear_rooms center = Vector(screen_size[0] / 2, screen_size[1] / 2) for i in range(linear_rooms): if (i == 0): r = Room( center, random.randrange(self.__min_width, self.__max_width, self.__tile_size), random.randrange(self.__min_height, self.__max_height, self.__tile_size), "start") elif (i == linear_rooms - 1): r = Room( center, random.randrange(self.__min_width, self.__max_width, self.__tile_size), random.randrange(self.__min_height, self.__max_height, self.__tile_size), "end") else: r = Room( center, random.randrange(self.__min_width, self.__max_width, self.__tile_size), random.randrange(self.__min_height, self.__max_height, self.__tile_size)) heading = self.__getRandomHeading() self.__rooms.append(r) if (i > 0): while (self.__rooms[i - 1].headingExists(heading)): heading = self.__getRandomHeading() self.__rooms[i - 1].addNeighbour(r, heading) r.addNeighbour(self.__rooms[i - 1], self.__invertHeading(heading)) for i in range(random_rooms): chosen_room = self.__rooms[random.randint(0, len(self.__rooms) - 1)] while (len(chosen_room.getEmptyNeighbours()) == 0 or chosen_room.isStart() or chosen_room.isEnd()): chosen_room = self.__rooms[random.randint( 0, len(self.__rooms) - 1)] heading = self.__getRandomHeading() while (chosen_room.headingExists(heading)): heading = self.__getRandomHeading() r = Room( center, random.randrange(self.__min_width, self.__max_width, self.__tile_size), random.randrange(self.__min_height, self.__max_height, self.__tile_size)) chosen_room.addNeighbour(r, heading) r.addNeighbour(chosen_room, self.__invertHeading(heading)) self.__rooms.append(r) self.__addEnemies() print("Map Generated")
def test_subtraction(): v1 = Vector(2,4) v2 = Vector(1,2) v3 = v1 - v2 assert v3.x == 1 assert v3.y == 2
def clickBtn(self): self.clicked = True self.trigger() # instead of using this the value should be bracketed to mean that it's a single arguement value #instances of all types, without brackets it points to a class but doesnt make an instance obj_explosion_spriteS=Spritesheet(Img_explosion,9,9,100,100,100,100,[9,9]) obj_usr_car_spriteS=Spritesheet(Img_user_Car,5,5,139,70,139,70,[4,4]) obj_user_car= User_Car(Vector((75,random.randrange(150,530)))) obj_Enemey_car=Enemy_Car(Vector((random.randrange(0,400),random.randrange(150,450))),Vector((1,0)),img_cars_array[random.randrange(0,5)]) obj_Tree=TreeAndWall() obj_Kbd=keyboard() obj_Int=Interaction(obj_user_car,obj_Kbd) def click(pos): for x in range(0, len(arrayButton)): if(arrayButton[x].contains(pos)):
def test_multiplication(): v1 = Vector(1,2) v2 = v1 * 2 assert v2.x == 2 assert v2.y == 4
def setUp(self): self.v1 = Vector(1, 2) self.v2 = Vector(2, 1)