Esempio n. 1
0
def nextTriangle(A,B,C):
  [B,C,A] = Vector.sort([A,B,C])
  D = B + C - A
  E = 3* (B+C)/ 2- 2*A
  F = (3* (B+C)- 2*A)/4
  G = (2* A+ B+ C)/4
  if F.cost() < G.cost():
    X = Vector(F)
  else:
    X = Vector(G)
  #case 1: vertex A moves to D or E
  if D.cost() < A.cost() and E.cost() < A.cost():
    A.equals(E)
  elif D.cost() < A.cost():
    A.equals(D)
  #case 2: vertex A moves to F or G
  elif X.cost() < A.cost():
    A.equals(X)
  #case 3: vertex A moves to H and vertex C moves to I
  else:
    H = (A + B)/2
    I = (B + C)/2
    A.equals(H)
    C.equals(I)
  return A,B,C
def Specular(aNormal,aTrianglePoint):
  eyeVector = [cameraX - aTrianglePoint[X],
               cameraY - aTrianglePoint[Y],
               cameraZ - aTrianglePoint[Z],
               1.0     - aTrianglePoint[3]]

  eyeVector = Vector.normalize(eyeVector)
 
  lightVec = [lightPoint[X] - aTrianglePoint[X],
              lightPoint[Y] - aTrianglePoint[Y],
              lightPoint[Z] - aTrianglePoint[Z],
              lightPoint[W] - aTrianglePoint[W]]
  
  lightVec = Vector.normalize(lightVec)

  #caculate the half vector
  H = [lightVec[X] + eyeVector[X],
       lightVec[Y] + eyeVector[Y],
       lightVec[Z] + eyeVector[Z],
       lightVec[W] + eyeVector[W]]

  #now normalize and dot the half with the normal vec,
  #use the shininess constant defined in IncludesAndConstants.py
  H = Vector.normalize(H)
  d = Vector.dotProduct(aNormal,H)
  return math.pow(max(d,0),shininess)
Esempio n. 3
0
 def resetControl(self):
     self.switch = 0
     self.error = Vector(0,0)
     self.errorPrev = Vector(0,0)        
     self.derror = Vector(0,0)        
     self.errorSum = Vector(0,0)
     self.program = None
Esempio n. 4
0
def oscillateCurve( curve, start=0.0, end=1.0, freq=1.0, ease=0.5, strength=1.0 ):
    """ Oscillates a given curve by moving each vertex in an alternating
        direction based on the normal.  This process takes place over the
        range defined by "start" and "end" as percentages of arc length.
        Oscillation eases to full strength as determined by the "ease" and
        "strength" arguments. """
    if(ease > (end-start)*0.5):
        ease = (end-start)*0.5
    if(start < end):
        CVs = mc.getAttr( curve+".cv[*]" )
        newCVs = findCVsInRange(curve, start, end)
        for (I,U,L) in newCVs:
            interp = (L-start)/(end-start)
            osc = sin(freq*interp)
            scale = pulse(start+ease, end, ease, L)  # ease must be between 0 and 0.5
## Don't use Maya's normalized normal -- it flip flops with curvature so it's not good for oscillating offset
#            normal = Vector(mc.pointOnCurve(curve, parameter=cv[1], normalizedNormal=True))
#            if(normal.mag() == 0.0):
#                print "Getting normal from up x tangent"
            normal = Vector(0,1,0)**Vector(mc.pointOnCurve(curve, parameter=U, tangent=True))
            normal = normal.norm()
            pos = Vector(CVs[I])
            pos = pos+normal*scale*strength*osc
            CVs[I] = pos.asTuple()

    for i,cv in enumerate(CVs):
        mc.setAttr(curve+".cv[%d]"%i, cv[0], cv[1], cv[2])

    return curve
Esempio n. 5
0
class Obstacle:
    def __init__(self,x,y,vx,vy):
        self.pos = Vector(x,y)
        self.vel = Vector(vx,vy)
        self.acc = Vector(0,1)
        self.c = color(random(60),random(80),random(255))
        self.radius = 10
        self.elasticity = 0.9
        self.dead = False
        self.life = 0
        self.inc = 1
    
    def isDead(self):
        return self.dead
    
    def getX(self):
        return self.pos.getX()
    
    def getY(self):
        return self.pos.getY()
    
    def getR(self):
        return self.radius
    
    def render(self):
        fill(self.c)
        wall = loadImage("Wall.png")       
        image(wall, self.pos.getX(),self.pos.getY())    
    def update(self):
        #Lifetime
        self.life += self.inc
        if self.life > 1000:
            self.dead = True
Esempio n. 6
0
	def reinit(self):
		self.pos = Vector(Conf.TURTLE.INIT_POS)
		self.heading = Vector(Conf.TURTLE.INIT_HEADING)
		self.color = Vector(colorsys.rgb_to_hls(Conf.TURTLE.INIT_COLOR[0], Conf.TURTLE.INIT_COLOR[1], Conf.TURTLE.INIT_COLOR[2]))
		self.vertexBuffer = []
		self.vertexBufferChanged = False
		self.vertexBufferLength = 0
		self.vertexPositions = vbo.VBO(np.array(self.vertexBuffer, dtype=np.float32))
		self.vertexPositions.bind()
Esempio n. 7
0
 def __init__(self,x,y,vx,vy):
     self.pos = Vector(x,y)
     self.vel = Vector(vx,vy)
     self.acc = Vector(0,1)
     self.c = color(random(60),random(80),random(255))
     self.radius = 10
     self.elasticity = 0.8
     self.dead = False
     self.life = 0
     self.inc = 1
Esempio n. 8
0
def execute(*args):
    """Test all derived functions for proper operation
    
    """
    
    import Vector
    reload(Vector)
    Vector.test()
    
    import Add
    reload(Add)
    Add.test()
    
    import Multiply
    reload(Multiply)
    Multiply.test()
    
    import Divide
    reload(Divide)
    Divide.test()
    
    import Difference
    reload(Difference)
    Difference.test()
    
    import Poly
    reload(Poly)
    Poly.test()
    
    import Average
    reload(Average)
    Average.test()
    
    import LinTrans
    reload(LinTrans)
    LinTrans.test()
    
    import Test
    reload(Test)
    Test.test()
    
    import Rotate
    reload(Rotate)
    Rotate.test()
    
    import Magnitude
    reload(Magnitude)
    Magnitude.test()
    
    import Cape
    reload(Cape)
    Cape.test()
    
    print "-"*60
    print "Function Test Complete"
Esempio n. 9
0
 def __init__(self, dt):
     self.dt = dt
     self.rotorspeed = Vector(0.0, 0.0)
     self.pos = Vector(0,0)
     self.speed = Vector(0.0,0.0)
     self.acc = Vector(0.0, 0.0)
     
     self.posPrev = Vector(0.0, 0.0)
     self.speedPrev = Vector(0.0, 0.0)
     
     self.control = None
Esempio n. 10
0
	def getMinMaxItems(self):
		self.itemMAX = Vector(self.iteminfo[0][0])
		self.itemMIN = Vector(self.iteminfo[0][0])
		self.itemMEAN = Vector(self.iteminfo[0][0])
		for idx in range(1, len(self.iteminfo)):
			self.itemMAX.upper( self.iteminfo[idx][0] )
			self.itemMIN.lower( self.iteminfo[idx][0] )
			self.itemMEAN += self.iteminfo[idx][0]
			#print self.iteminfo[idx][0].str()
			#print self.itemMAX.str()
			#print self.itemMIN.str()
		self.itemMEAN /= len(self.iteminfo)
Esempio n. 11
0
def Diffuse(aNormal,aTrianglePoint):
  lightVec = [ lightPoint[X] - aTrianglePoint[X],
               lightPoint[Y] - aTrianglePoint[Y],
               lightPoint[Z] - aTrianglePoint[Z],
               lightPoint[W] - aTrianglePoint[W]]

  lightVec = Vector.normalize(lightVec)
  #print(lightVec[X],lightVec[Y],lightVec[Z])
  #print(Vector.length(lightVec))
  aNormal = Vector.normalize(aNormal)

  return max(Vector.dotProduct(lightVec,aNormal),0)  
Esempio n. 12
0
    def createDendrites(self):
        angle           = 360.0/self.branches
        startDist       = 0.95 * self.somaSize
        endDist         = startDist + self.stepDist
        halfThickness   = self.dendriteThickness/2.0
        
        a = 0.0
        while a<360.0:
            
            # Define the points that the dendrite would follow if it were a line (i.e. no thickness)
            initialResources = self.maxRadius 
            p1, p2 = Vector(), Vector()
            p1.x = m.cos(m.radians(a)) * startDist + self.center.x
            p1.y = m.sin(m.radians(a)) * startDist + self.center.y
            p2.x = m.cos(m.radians(a)) * endDist + self.center.x
            p2.y = m.sin(m.radians(a)) * endDist + self.center.y
            remainingResources = initialResources - p1.distance(p2)

            # Find the first and last vertex of the quad (moving perpendicular from p1 to create thickness)
            t = p1 - self.center
            leftPerp    = t.leftXYPerpendicular().normalize()
            rightPerp   = t.rightXYPerpendicular().normalize()
            v1 = leftPerp * halfThickness + p1
            v4 = rightPerp * halfThickness + p1

            # Find the second and third vertex of the quad (moving perpendicular from p2 to create thickness)
            t = p2 - p1
            leftPerp    = t.leftXYPerpendicular().normalize()
            rightPerp   = t.rightXYPerpendicular().normalize()
            v2 = leftPerp * halfThickness + p2
            v3 = rightPerp * halfThickness + p2

            # Find the vertex index of the newly added vertices
            startVertexNumber = len(self.verts)
            v1Number = startVertexNumber
            v2Number = startVertexNumber + 1
            v3Number = startVertexNumber + 2
            v4Number = startVertexNumber + 3

            # Add the vertices
            self.verts = self.verts + [v1.toList(), v2.toList(), v3.toList(), v4.toList()]

            # Add a properly ordered face
            face = self.createOrderedQuad(v1, v2, v3, v4, v1Number, v2Number, v3Number, v4Number)
            self.faces.append(face)

            # Store some information about the current dendrite branch
            self.dendrites.append([[a,initialResources,p1,[v1,v1Number],[v4,v4Number]],
                                   [a,remainingResources,p2,[v2,v2Number],[v3,v3Number]]])
            self.lineSegments.append([p1, (p1+p2)/2.0, p2])
            self.updateRadius(v1, v2, v3, v4)
            a += angle
Esempio n. 13
0
def runRandomSearch():
  startTime = clock()
  vector = Vector(random()*DOMAIN_LIMIT,random()*DOMAIN_LIMIT)
  minc= vector.cost()
  while(clock() - startTime < MAX_RUN_TIME):
    global PROBE_COUNT1
    PROBE_COUNT1+=1
    vector = Vector(random()*DOMAIN_LIMIT,random()*DOMAIN_LIMIT)
    if(vector.cost() < minc):
      minc = vector.cost()
  print('2. Random Probing used', PROBE_COUNT1, 'probes.')
  print('Vector =', vector, 'Cost =', round(minc,5))
  print('---Search time =', round(clock() - startTime, 2), 'seconds\n')
Esempio n. 14
0
def TestForCull(aTriangle):
  camVector = [IncludesAndConstants.lookPointX - IncludesAndConstants.cameraX,
               IncludesAndConstants.lookPointY - IncludesAndConstants.cameraY,
               IncludesAndConstants.lookPointZ - IncludesAndConstants.cameraZ,0]

  camVector = Vector.normalize(camVector)

  normal = [aTriangle.normal[X],aTriangle.normal[Y],aTriangle.normal[Z],0]
  normal = Vector.normalize(normal)

  if Vector.dotProduct(camVector,normal) <= 0.0:
    return True
  else:
    return False
Esempio n. 15
0
def testAssignmentOperators() :
   V = Vector([1.0, 2.0, 3.0])
   print V.size()
   V.show()
   W = V
   W.show()
   for k in range(V.size()) :
      print V[k]
   for k in range(V.size()) :
      V[k] = 0.0
   V.show()
Esempio n. 16
0
 def __init__(self, drone):
     self.drone = drone
     self.error = Vector(0,0)
     self.errorPrev = Vector(0,0)
     
     self.derror = Vector(0,0)
     self.errorSum = Vector(0,0)
     
     self.program = ""
     self.params = []
     self.switch = 0
     
     self.p = [1.920992106546498, 1.4674037935865036, 1.2306011558472907]
     
     drone.setControl(self)
Esempio n. 17
0
 def __init__(self):
     self.up = Vector([0,1,0])
     self.position = Vector([0,0,-5])
     self.lookat = Vector([0,0,0])
     self.keysDown = {}
     self.keysDownSpecial = {}
     self.debug = None
Esempio n. 18
0
    def initializeGrowth(self, stepSize, heading, headingRange):        
        self.p2     = Vector()
        self.p2.x   = m.cos(m.radians(heading)) * stepSize + self.p1.x
        self.p2.y   = m.sin(m.radians(heading)) * stepSize + self.p1.y
        
        thickness = (self.resources/self.maxResources) * (self.startThickness - self.endThickness) + self.endThickness
        halfThickness = thickness / 2.0

        t           = self.p1 - self.cellCenter
        leftPerp    = t.leftXYPerpendicular().normalize()
        rightPerp   = t.rightXYPerpendicular().normalize()
        self.v1     = leftPerp * halfThickness + self.p1
        self.v4     = rightPerp * halfThickness + self.p1

        t           = self.p2 - self.p1
        leftPerp    = t.leftXYPerpendicular().normalize()
        rightPerp   = t.rightXYPerpendicular().normalize()
        self.v2     = leftPerp * halfThickness + self.p2
        self.v3     = rightPerp * halfThickness + self.p2

        self.vertices   = self.vertices + [self.v1] + [self.v2] + [self.v3] + [self.v4]
        self.points     = self.points + [self.p1] + [self.p2]
        
        self.resources -= stepSize
        if self.resources <= 0: self.growing = False
Esempio n. 19
0
def storeresponse(answers):
    answersstr = "', '".join(answers)


    db = sql()
    cur = db[0]
    conn = db[1]
    #conn = sql()[1]
    #cur = sql()[0]

    print "***************************"
    query = "INSERT INTO sjsu.User_Response (SJSU_ID, Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10, Q11, Q12, Q13, Q14, Q15, Q16, Q17, Q18, Q19, Q20, Major) VALUES('" + answersstr + "', NULL)"
    print query
    cur.execute(query)
    print "***************************"
    last_id = str(cur.lastrowid)
    print "***************************"
    print "Your User Response ID is " + last_id +"."
    #cur.commit()

    # Seperate function?
    qanswers = map(int,answers[1:])
    recommendation = Vector.distcheck(qanswers)
    print ("Your recommended major is: " + recommendation[0])
    cur.execute("UPDATE User_Response SET Rec_Major = '" + recommendation[1] + "' WHERE User_Response_ID = " + last_id)
Esempio n. 20
0
	def plotTriangle(self, triangle):
		v0 = self.project(triangle.p1)
		v1 = self.project(triangle.p2)
		v2 = self.project(triangle.p3)
		v0.z = 1.0/v0.z
		v1.z = 1.0/v1.z
		v2.z = 1.0/v2.z
		
		x_min = int(min(v0.x, v1.x, v2.x))
		x_max = int(max(v0.x, v1.x, v2.x) + 1)
		y_min = int(min(v0.y, v1.y, v2.y))
		y_max = int(max(v0.y, v1.y, v2.y) + 1)

		x_min = max(0, x_min)
		x_max = min(self.width, x_max)
		y_min = max(0, y_min)
		y_max = min(self.height, y_max)
		
		area = self.edgeFunction(v0, v1, v2)
		
		for x in range(x_min, x_max):
			for y in range(y_min, y_max):
				p = Vector(x,y,0)
				
				w0 = self.edgeFunction(v1, v2, p)
				w1 = self.edgeFunction(v2, v0, p)
				w2 = self.edgeFunction(v0, v1, p)
				if w0 >= 0 and w1 >= 0 and w2 >=0:
					w0 /= area
					w1 /= area
					w2 /= area
					z = (1.0/(v0.z * w0 + v1.z * w1 +  v2.z * w2))
					if (z < self.depth_buffer[y][x]):
						self.depth_buffer[y][x] = z
						v0cam = self.world_matrix.transformPoint(triangle.p1)
						v1cam = self.world_matrix.transformPoint(triangle.p2)
						v2cam = self.world_matrix.transformPoint(triangle.p3)
						px = (v0cam.x/-v0cam.z) * w0 + (v1cam.x/-v1cam.z) * w1 + (v2cam.x/-v2cam.z) * w2 
						py = (v0cam.y/-v0cam.z) * w0 + (v1cam.y/-v1cam.z) * w1 + (v2cam.y/-v2cam.z) * w2

						pt = Vector(px * z, py * z, z)
						
						n = (v1cam - v0cam).cross(v2cam - v0cam).normalized()
						view_direction = pt.normalized()
						view_direction = Vector(-pt.x, -pt.y, -pt.z).normalized()
						cosine = max(0, n.dot(view_direction))
						self.plotPoint(x,y, cosine * 255)
Esempio n. 21
0
    def growDendrite(self, i):
        dendrite        = self.dendrites[i]
        step            = self.stepDist
        halfThickness   = self.dendriteThickness/2.0

        # Load this dendrite's information
        heading         = dendrite[-1][0]
        resources       = dendrite[-1][1]
        p1              = dendrite[-1][2]
        v1, v1Number    = dendrite[-1][3]
        v4, v4Number    = dendrite[-1][4]

        thickness = resources/self.maxRadius * (self.dendriteThickness - self.minDendriteThickness) + self.minDendriteThickness
        halfThickness = thickness / 2.0

        # Generate a random heading in order to create p2
        heading += r.uniform(-self.headingRange, self.headingRange)
        p2      = Vector()
        p2.x    = p1.x + m.cos(m.radians(heading)) * step
        p2.y    = p1.y + m.sin(m.radians(heading)) * step
        resources = resources - p1.distance(p2)

        # Calculate the new vertices of the quad (adding thickness)
        t = p2 - p1
        leftPerp    = t.leftXYPerpendicular().normalize()
        rightPerp   = t.rightXYPerpendicular().normalize()
        v2 = leftPerp * halfThickness + p2
        v3 = rightPerp * halfThickness + p2
        
        # Find the vertex index of the newly added vertices
        startVertexNumber = len(self.verts)
        v2Number = startVertexNumber
        v3Number = startVertexNumber + 1
        
        # Add the vertices
        self.verts = self.verts + [v2.toList(), v3.toList()]
        
        # Add a properly ordered face
        face = self.createOrderedQuad(v1, v2, v3, v4, v1Number, v2Number, v3Number, v4Number)
        self.faces.append(face)

        # Store some information about the current dendrite branch
        self.dendrites[i].append([heading, resources, p2, [v2,v2Number], [v3,v3Number]])
        self.lineSegments.append([p1, (p1+p2)/2.0, p2])
        self.updateRadius(v1, v2, v3, v4)
Esempio n. 22
0
 def distance_to_r(self):
     '''
     :return: return the cat radius
     '''
     self.r = Vector(450, 350).distance(self.position)
     if self.r < 90:
         self.position = Vector(600,350)
         self.r = Vector(450, 350).distance(self.position)
     return self.r
Esempio n. 23
0
def CreateTransformedNormal(aTriangle):

  vec1 = [aTriangle.p1[X] - aTriangle.p2[X],aTriangle.p1[Y] - aTriangle.p2[Y],
          aTriangle.p1[Z] - aTriangle.p2[Z]]

  vec2 = [aTriangle.p3[X] - aTriangle.p2[X],aTriangle.p3[Y] - aTriangle.p2[Y],
          aTriangle.p3[Z] - aTriangle.p2[Z]]

  aTriangle.normal = Vector.crossProduct(vec2,vec1)

  return aTriangle.normal
Esempio n. 24
0
	def __init__(self, pos=None):
		if pos is None:
			self.pos = Vector(Conf.TURTLE.INIT_POS)
		else:
			self.pos = Vector(pos)
		self.heading = Vector(Conf.TURTLE.INIT_HEADING)
		self.color = Vector(colorsys.rgb_to_hls(Conf.TURTLE.INIT_COLOR[0], Conf.TURTLE.INIT_COLOR[1], Conf.TURTLE.INIT_COLOR[2]))

		self.stateStack = [] # allow to manage a stack of states
		self.stochasticFactor = 0 # used to randomize drawing

		# the vertex buffer is a liste of lists : [[x y z r g b time],...]
		self.vertexBuffer = []
		self.vertexBufferLength = 0
		self.vertexBufferChanged = False
		self.vertexPositions = None
		#indices = np.array([[0,1,2], [0, 3, 2]], dtype=np.int32)
		self.draw_type = GL_TRIANGLES

		self.point()
Esempio n. 25
0
 def ClosestTimeTo( self, point, plane=None ):
     """ Returns the closest point in this trajectory to the given point in 3d space (or 2d if plane is defined) """
     if not type(point) == Vector:
         point = Vector(point)
     if plane:
         point = point.projectToPlane(plane.normal,planePt=plane.point)
     minDist = float("inf")
     ft = None
     camPos = Vector( mc.xform(mc.lookThru(q=True), q=True, t=True) )
     for i,t in enumerate(sorted(self.points.keys())):
         p = self.points[t]
         if plane:
             p = p.projectToPlane(plane.normal,planePt=plane.point)
             dist = (point-p).mag()
         else:
             ray = (p-camPos).norm()     # build a ray from the camera to the path point in question
             dist = ray.cross(point-p).mag()
         if minDist > dist:
             minDist = dist
             ft = t
     return ft   # return the key of the closest point in the points dictionary
Esempio n. 26
0
def testVectorOperators() :
   V = Vector([0.0, 1.0, 2.0])
   W = Vector([3.0, 4.0, 5.0])
   print V.dot(W)
   print V.norm()
   U = V.cross(W)
   U.show()
Esempio n. 27
0
def step(p1,p2):#radius=1
  X1 = Vector(p1,p2)
  for t in frange(0, pi*2, pi/4):
    X = Vector(p1 + (cos(t)), p2 + (sin(t)))
    if X.cost() < X1.cost():
      X1.equals(X)
  return X1
    def __init__(self):
        self.image = 17
        self.framenumber = 0
        self.swinging = 4;
        self.gunmode = False;
        pygame.sprite.Sprite.__init__(self)
        self.images = [pygame.image.load(os.path.join(os.curdir, 'spritel1.png')).convert_alpha(),
                    pygame.image.load(os.path.join(os.curdir, 'spritel2.png')).convert_alpha(),
                    pygame.image.load(os.path.join(os.curdir, 'spritel3.png')).convert_alpha(),
                    pygame.image.load(os.path.join(os.curdir, 'spritel4.png')).convert_alpha(),
                    pygame.image.load(os.path.join(os.curdir, 'spritel5.png')).convert_alpha(),
                    pygame.image.load(os.path.join(os.curdir, 'spritel6.png')).convert_alpha(),
                    pygame.image.load(os.path.join(os.curdir, 'spritel7.png')).convert_alpha(),
                    pygame.image.load(os.path.join(os.curdir, 'spritel8.png')).convert_alpha(),
                    pygame.image.load(os.path.join(os.curdir, 'spriter1.png')).convert_alpha(),
                    pygame.image.load(os.path.join(os.curdir, 'spriter2.png')).convert_alpha(),
                    pygame.image.load(os.path.join(os.curdir, 'spriter3.png')).convert_alpha(),
                    pygame.image.load(os.path.join(os.curdir, 'spriter4.png')).convert_alpha(),
                    pygame.image.load(os.path.join(os.curdir, 'spriter5.png')).convert_alpha(),
                    pygame.image.load(os.path.join(os.curdir, 'spriter6.png')).convert_alpha(),
                    pygame.image.load(os.path.join(os.curdir, 'spriter7.png')).convert_alpha(),
                    pygame.image.load(os.path.join(os.curdir, 'spriter8.png')).convert_alpha(),
                    pygame.image.load(os.path.join(os.curdir, 'jump.png')).convert_alpha(),
                    pygame.image.load(os.path.join(os.curdir, 'start.png')).convert_alpha(),
                    pygame.image.load(os.path.join(os.curdir, 'bowl.png')).convert_alpha(),
                    pygame.image.load(os.path.join(os.curdir, 'bowr.png')).convert_alpha(),
                    pygame.image.load(os.path.join(os.curdir, 'hurt.png')).convert_alpha(),
                    pygame.image.load(os.path.join(os.curdir, 'dead.png')).convert_alpha()
                    ]

        self.rect = self.images[self.image].get_rect()
        self.rect = self.rect.move(300,600)
        self.vel = 0
        self.x = 300
        self.y = 600
        self.dir = 1 # 1: Right -1: Left
        self.vector = Vector(self.x,self.y)
        self.Arrows = 20
        self.ArrowsMax = 20
        self.ArrowsRepl = 0.0
        self.ArrowsReplRate = 0.1
        self.Gravity = 100
        self.GravityRepl = 0.0
        self.RapidFire = False
        self.MultiShot = False
        self.MultiShot2 = False
        self.Lives = 5
        self.Repel = 8
        self.DecoyNum = 5
        self.DecoyCounter = 0
        self.DecoyX = 0
        self.DecoyY = 0
Esempio n. 29
0
def noiseCurve( curve, start=0.0, end=1.0, freq=1.0, ease=0.5, strength=1.0 ):
    """ Adds noise to a given curve by moving each vertex with Perlin
        noise based on the normal.  This process takes place over the
        range defined by "start" and "end" as percentages of arc length.
        Noise eases to full strength as determined by the "ease" and
        "strength" arguments. """
    if(ease > (end-start)*0.5):         # ease must be between 0 and 0.5
        ease = (end-start)*0.5
    if(start < end):
        CVs = mc.getAttr( curve+".cv[*]" )
        newCVs = findCVsInRange(curve, start, end)
        for (I,U,L) in newCVs:
            interp = (L-start)/(end-start)
            noiz = noise(freq*interp)
            scale = pulse(start+ease, end, ease, L)  
            normal = Vector(0,1,0)**Vector(mc.pointOnCurve(curve, parameter=U, tangent=True))
            normal = normal.norm()
            pos = Vector(CVs[I])
            pos = pos+normal*scale*strength*noiz
            CVs[I] = pos.asTuple()
    for i,cv in enumerate(CVs):
        print(curve+".cv[%d]"%cv[0], cv[0], cv[1], cv[2])
        mc.setAttr(curve+".cv[%d]"%i, cv[0], cv[1], cv[2])
Esempio n. 30
0
    def regularGrowth(self, stepSize=None, heading=None, headingRange=None):
        # Start growing from the last dendrite points (deep copies)
        self.p1 = self.p2.copyVector()
        self.v1 = self.v2.copyVector()
        self.v4 = self.v3.copyVector()

        # Unlink any references that exist
        self.p2 = Vector()
        self.v2 = Vector()
        self.v3 = Vector()
        
        # Map the resources remaining into the range of thickness values to obtain the current thickness
        thickness       = remap(self.resources, 0.0, self.maxResources, self.startThickness, self.endThickness)
        halfThickness   = thickness / 2.0

        # Generate a random heading
        heading += r.uniform(-self.headingRange, self.headingRange)

        # Find p2 by moving in the heading direction
        self.p2.x = self.p1.x + m.cos(m.radians(heading)) * stepSize
        self.p2.y = self.p1.y + m.sin(m.radians(heading)) * stepSize

        # Calculate the new vertices of the quad (adding thickness relative to p2)
        t           = self.p2 - self.p1
        leftPerp    = t.leftXYPerpendicular().normalize()
        rightPerp   = t.rightXYPerpendicular().normalize()
        self.v2     = leftPerp * halfThickness + self.p2
        self.v3     = rightPerp * halfThickness + self.p2

        # Store the new vertices and the new point
        self.vertices   = self.vertices + [self.v2] + [self.v3]
        self.points     = self.points + [self.p2]
        
        # Update the resources based on distance traveled            
        self.resources -= stepSize        
        if self.resources <= 0: self.growing = False
 def __init__(self,solver,a=Vector.Vector(x=0,y=0,z=-9.81),c=0):
     self.solver = solver
     self.a = a
     self.c = c
Esempio n. 32
0
 def testArea(self):
     c = Vector.Vector([0, 0])
     r = 1
     o = Circle.Circle(c, r)
     self.assertEqual(o.area(), math.pi)
Esempio n. 33
0
 def position(self):
     return Vector(x, y)
Esempio n. 34
0
class Vehicle:
    def __init__(self, x, y, world):
        self.pos = Vector(x, y)
        self.vel = Vector(1, 0)
        self.acc = Vector(0, 0)

        self.maxSpeed = 6
        self.maxForce = .5

        self.size = 10  # radius

        self.world = world

    def borders(self):
        if self.pos.x < -self.size:
            self.pos.x = self.world.width + self.size

        elif self.pos.x > self.world.width + self.size:
            self.pos.x = -self.size

        if self.pos.y < -self.size:
            self.pos.y = self.world.height + self.size

        elif self.pos.y > self.world.height + self.size:
            self.pos.y = -self.size

    def run(self):
        self.borders()
        self.update()

    def update(self):
        self.vel.add(self.acc)
        self.vel.limitMag(self.maxSpeed)
        self.pos.sub(self.vel)
        self.acc.set(0, 0)

    def applyForce(self, force):
        # can add mass a = f / m
        self.acc.add(force)

    def seek(self, target):
        desired = Vector.subTwo(self.pos, target)
        desired.setMag(self.maxSpeed)
        steer = Vector.subTwo(desired, self.vel)
        steer.limitMag(self.maxForce)

        return steer

    def arrive(self, target):
        desired = Vector.subTwo(self.pos, target)

        speed = self.maxSpeed
        if desired.getMag() < 100:
            speed = mapNum(desired.getMag(), 0, 100, 0, self.maxSpeed)

        desired.limitMag(speed)

        steer = Vector.subTwo(desired, self.vel)
        steer.limitMag(self.maxForce)

        return steer

    def avoid(self, target):
        steer = self.seek(target)
        return steer.mult(Vector(-1, -1))

    def randomness(self):
        steer = Vector.getRndVec(-1, 1)
        steer.limitMag(self.maxForce)

        return steer

    def rebound(self):
        distance = Vector.getDis(self.pos, self.world.center)
        if distance > self.world.center_dis != 0:
            return self.seek(self.world.center)
        else:
            return Vector(0, 0)

    def getVerts(self):
        verts = np.zeros((4, 2), dtype=int)

        bot_point = self.vel.copy()
        bot_point.setMag(self.size)
        top_point = bot_point.getFliped()

        bot_point.div(Vector(
            np.sqrt(2), np.sqrt(2)))  # get sqrt 2 from a constant in math lib

        perp = top_point.getPerp()
        right_point = Vector.addTwo(bot_point, perp)
        left_point = Vector.subTwo(bot_point, perp)

        bot_point.mult(Vector(.6, .6))

        verts[0, :] = Vector.addTwo(top_point, self.pos).toArr()
        verts[1, :] = Vector.addTwo(right_point, self.pos).toArr()
        verts[2, :] = Vector.addTwo(bot_point, self.pos).toArr()
        verts[3, :] = Vector.addTwo(left_point, self.pos).toArr()

        return verts

    def draw(self, arr):
        x, y = (int(self.pos.x), int(self.pos.y))
        cv2.circle(arr, (x, y), self.size,
                   [mapNum(self.vel.getMag(), 0, self.maxSpeed, 51, 255)] * 3,
                   -1)
Esempio n. 35
0
import Vector

myVector = Vector.Vector([1, 2, 3])
print(myVector.__str__())
print(myVector.__eq__([2, 1, 2]))
Esempio n. 36
0
 def randomFlagLocation(self):
     import vsrandom
     if (len(self.flags)):
         i = vsrandom.randrange(0,len(self.flags))
         return Vector.Add((vsrandom.uniform(-20,20),vsrandom.uniform(-20,20),vsrandom.uniform(-20,20)),self.flags[i].Position())
     return (0,0,0)
Esempio n. 37
0
			start += Vector((randrange(3) - 1) * Constants.GRID_SIZE, (randrange(3) - 1) * Constants.GRID_SIZE)
			while(start.x >= Constants.WORLD_WIDTH - Constants.GRID_SIZE or start.y >= Constants.WORLD_HEIGHT - Constants.GRID_SIZE):
				start += Vector((randrange(3) - 1) * Constants.GRID_SIZE, (randrange(3) - 1) * Constants.GRID_SIZE)
			graph.placeObstacle(start, (0, 0, 0))

#################################################################################
# Main Functionality
#################################################################################

pygame.init();

screen = pygame.display.set_mode((Constants.WORLD_WIDTH, Constants.WORLD_HEIGHT))
clock = pygame.time.Clock()
sheepImage = pygame.image.load('sheep.png')
dogImage = pygame.image.load('collie.png')
bounds = Vector(Constants.WORLD_WIDTH, Constants.WORLD_HEIGHT)

# Setup the graph
graph = Graph()

# Setup the dog
dog = Player(dogImage, Vector(Constants.WORLD_WIDTH * .5, Constants.WORLD_HEIGHT * .5), 
			 Vector(Constants.DOG_WIDTH, Constants.DOG_HEIGHT), (0, 255, 0), 
			 Constants.DOG_SPEED, Constants.DOG_ANGULAR_SPEED)
print (dog.center)
# Setup the sheep (only 1 for now...)
herd = []
sheep = Sheep(sheepImage, Vector(randrange(int(bounds.x * .4), int(bounds.x * .6)), randrange(int(bounds.y * .6), int(bounds.y * .8))), Vector(Constants.DOG_WIDTH, Constants.DOG_HEIGHT), (0, 255, 0), Constants.SHEEP_SPEED, Constants.SHEEP_ANGULAR_SPEED)
#sheep = Sheep(sheepImage, Vector(100,200), Vector(16,32), (0,255,0), 5, 5)
herd.append(sheep)
Esempio n. 38
0
 def getshape(self):
     """Return a list of vectors giving the polygon for this turtle."""
     return [
         self.position + Vector(0, 5), self.position - Vector(5, 0),
         self.position - Vector(0, 5), self.position + Vector(5, 0)
     ]
Esempio n. 39
0
    def select_next_action(self):
        #Scan the radar
        self._dynamic_radar_data = self._radar.scan_dynamic_obstacles(
            self._gps.location())
        self._radar_data = self._radar.scan(self._gps.location())

        # Give the current observation to the obstacle motion predictor
        self.debug_info[
            'future_obstacles'] = self._obstacle_predictor.add_observation(
                self._gps.location(), self._radar_data,
                self._dynamic_radar_data,
                self._obstacle_predictor_dynobs_getter_func)

        if self._last_solution_node.data[:2] != (int(
                self._gps.location()[0]), int(self._gps.location()[1])):
            self._solution.insert(0, self._last_solution_node)

        self._pruneAndPrepend()

        if not self._rrt.hasGoal(self._targetpos, self._goalThreshold):
            self._rrt = Tree(
                Node((self._gps.location()[0], self._gps.location()[1],
                      self._time)))
            qgoal = Node(
                (self._targetpos[0], self._targetpos[1],
                 self._minTimeMultiplier *
                 self._minTime(self._gps.location(), self._targetpos)))
            self._status = self._grow_rrt(self._rrt, qgoal,
                                          self._goalThreshold, True)
            self._extract_solution()

        if self._status == 0:
            #There is a valid path from robot to goal
            while 0 < len(self._solution) and (
                    Vector.distance_between(self._gps.location(),
                                            self._solution[0].data[:2]) < 1.5
                    or self._solution[0].data[2] <= self._time):
                del self._solution[0]

            timeDiff = self._solution[0].data[2] - self._time
            #Should always be > 0
            direction = Vector.degrees_between(self._gps.location(),
                                               self._solution[0].data[:2])
            dist = min(
                self._maxstepsize,
                Vector.distance_between(self._gps.location(),
                                        self._solution[0].data[:2]) / timeDiff)
            self.debug_info["path"] = self._solution
            self._last_solution_node = self._solution[0]
            self._time += 1
        if self._status == 1:
            #No valid path found
            self._has_given_up = True
            dist = 0
            direction = np.random.uniform(low=0, high=360)
        if self._status == 2:
            #Robot or goal is inside dynamic obstacle
            dist = 0
            direction = np.random.uniform(low=0, high=360)

        return RobotControlInput(dist, direction)
Esempio n. 40
0
def createConvexPolygon(s):
    v = VectorInput.getVectorList(s)
    if len(v) < 3:
        raise Exception("Less than 3 vertices")
    Vector.sortVector(v)
    return ConvexPolygon(v)
Esempio n. 41
0
 def motion(self, event):
     drag = Vector(event.x, event.y)
     if self.dragging:
         self.dragging.position = self.start + drag - self.dragstart
         self.update(self.dragging)
Esempio n. 42
0
from Tkinter import *  # Import everything from Tkinter
from Arena import Arena  # Import our Arena
from Turtle import Turtle  # Import our Turtle
from Vector import *  # Import everything from our Vector

Turtle.m = 50.0  # Scaling factor
Turtle.origin = Vector(400, 300)
from Statue import *
from Mouse import *
from Cat import *

statue = Statue(Turtle.origin + Vector(0, 0), 0)
mouse = Mouse(Turtle.origin + Vector(0, -Turtle.m).rotate(40), 0)
cat = Cat(Turtle.origin + Vector(0, -4 * Turtle.m).rotate(200), 0, mouse)

tk = Tk()  # Create a Tk top-level widget
arena = Arena(tk, 800, 600)  # Create an Arena widget, arena
arena.pack()  # Tell arena to pack itself on screen
arena.add(statue)  # Add a very simple, statue
arena.add(mouse)  # Add a green mouse centered at the base of the statue
arena.add(cat)  # Add a red cat
tk.mainloop()  # Enter the Tkinter event loop
Esempio n. 43
0
import os
from Vector import *

# FIXED CONSTANTS
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
VIRTUAL_SIZE = Vector(1280, 720)

# CHANGEABLE CONSTANTS
SAMPLES = 4  # anti-aliasing
Esempio n. 44
0
 def testPerimeter(self):
     c = Vector.Vector([0, 0])
     r = 1
     o = Circle.Circle(c, r)
     self.assertEqual(o.perimeter(), 2 * math.pi)
Esempio n. 45
0
# Accepts response id as system argument

import Vector
import ConnectInfo
import sys

response_id = str(sys.argv[1])

db = ConnectInfo.sql()
cur = db[0]
conn = db[1]
sql = "select Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10, Q11, Q12, Q13, Q14, Q15, Q16, Q17, Q18, Q19, Q20 from User_Response where User_Response_ID=" + response_id
answerssql = cur.execute(sql)
answers = cur.fetchall()
qanswers = map(int, answers[0])
recommendation = Vector.distcheck(qanswers)
#print ("Your recommended major is: " + recommendation[0])
cur.execute("UPDATE User_Response SET Rec_Major = '" + recommendation[0] +
            "' WHERE User_Response_ID = " + response_id)
Esempio n. 46
0
	def drawCubo(self):
		CUBO = [
			v.Vector3D( self.radius + self.center.x, self.radius + self.center.y, self.radius + self.center.z),
			v.Vector3D(-self.radius + self.center.x, self.radius + self.center.y, self.radius + self.center.z),
			v.Vector3D(-self.radius + self.center.x,-self.radius + self.center.y, self.radius + self.center.z),
			v.Vector3D( self.radius + self.center.x,-self.radius + self.center.y, self.radius + self.center.z),
			v.Vector3D( self.radius + self.center.x, self.radius + self.center.y,-self.radius + self.center.z),
			v.Vector3D(-self.radius + self.center.x, self.radius + self.center.y,-self.radius + self.center.z),
			v.Vector3D(-self.radius + self.center.x,-self.radius + self.center.y,-self.radius + self.center.z),
			v.Vector3D( self.radius + self.center.x,-self.radius + self.center.y,-self.radius + self.center.z)
		]

		#for i in range(0, 8):
		#	CUBO[i] = CUBO[i].inversion(3)

		self.setCube()
		glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE)
		glFrontFace(GL_CCW);
		glEnable(GL_CULL_FACE)
		glCullFace(GL_BACK)
		glBegin(GL_POLYGON)
		#glNormal3d(normal0, normal1, normal2)
		glColor3f(0, 0, 255)
		glVertex3f(CUBO[0].x, CUBO[0].y, CUBO[0].z)
		glVertex3f(CUBO[1].x, CUBO[1].y, CUBO[1].z)
		glColor3f(255, 0, 0)
		glVertex3f(CUBO[2].x, CUBO[2].y, CUBO[2].z)
		glVertex3f(CUBO[3].x, CUBO[3].y, CUBO[3].z)
		glEnd()

		glFrontFace(GL_CCW);
		glEnable(GL_CULL_FACE)
		glCullFace(GL_BACK)
		glBegin(GL_POLYGON)
		#glNormal3d(normal0, normal1, normal2)
		glColor3f(0, 0, 255)
		glVertex3f(CUBO[7].x, CUBO[7].y, CUBO[7].z)
		glVertex3f(CUBO[6].x, CUBO[6].y, CUBO[6].z)
		glColor3f(255, 0, 0)
		glVertex3f(CUBO[5].x, CUBO[5].y, CUBO[5].z)
		glVertex3f(CUBO[4].x, CUBO[4].y, CUBO[4].z)
		glEnd()

		glFrontFace(GL_CCW);
		glEnable(GL_CULL_FACE)
		glCullFace(GL_BACK)
		glBegin(GL_POLYGON)
		#glNormal3d(normal0, normal1, normal2)
		glColor3f(0, 0, 255)
		glVertex3f(CUBO[0].x, CUBO[0].y, CUBO[0].z)
		glVertex3f(CUBO[3].x, CUBO[3].y, CUBO[3].z)
		glColor3f(255, 0, 0)
		glVertex3f(CUBO[7].x, CUBO[7].y, CUBO[7].z)
		glVertex3f(CUBO[4].x, CUBO[4].y, CUBO[4].z)
		glEnd()

		glFrontFace(GL_CCW);
		glEnable(GL_CULL_FACE)
		glCullFace(GL_BACK)
		glBegin(GL_POLYGON)
		#glNormal3d(normal0, normal1, normal2)
		glColor3f(0, 0, 255)
		glVertex3f(CUBO[1].x, CUBO[1].y, CUBO[1].z)
		glVertex3f(CUBO[5].x, CUBO[5].y, CUBO[5].z)
		glColor3f(255, 0, 0)
		glVertex3f(CUBO[6].x, CUBO[6].y, CUBO[6].z)
		glVertex3f(CUBO[2].x, CUBO[2].y, CUBO[2].z)
		glEnd()

		glFrontFace(GL_CCW);
		glEnable(GL_CULL_FACE)
		glCullFace(GL_BACK)
		glBegin(GL_POLYGON)
		#glNormal3d(normal0, normal1, normal2)
		glColor3f(0, 0, 255)
		glVertex3f(CUBO[2].x, CUBO[2].y, CUBO[2].z)
		glVertex3f(CUBO[6].x, CUBO[6].y, CUBO[6].z)
		glColor3f(255, 0, 0)
		glVertex3f(CUBO[7].x, CUBO[7].y, CUBO[7].z)
		glVertex3f(CUBO[3].x, CUBO[3].y, CUBO[3].z)
		glEnd()

		glFrontFace(GL_CCW);
		glEnable(GL_CULL_FACE)
		glCullFace(GL_BACK)
		glBegin(GL_POLYGON)
		#glNormal3d(normal0, normal1, normal2)
		glColor3f(0, 0, 255)
		glVertex3f(CUBO[1].x, CUBO[1].y, CUBO[1].z)
		glVertex3f(CUBO[0].x, CUBO[0].y, CUBO[0].z)
		glColor3f(255, 0, 0)
		glVertex3f(CUBO[4].x, CUBO[4].y, CUBO[4].z)
		glVertex3f(CUBO[5].x, CUBO[5].y, CUBO[5].z)
		glEnd()





#c = cube(v.Vector3D(0, 0, 0), 1)
#c.drawCube()
Esempio n. 47
0
 def toonear (self,vec,un):
     vec= Vector.Sub(un.Position(),vec)
     if (Vector.Dot(vec,vec)<1000):
         return True
     return False
Esempio n. 48
0
 def avoid(self, target):
     steer = self.seek(target)
     return steer.mult(Vector(-1, -1))
Esempio n. 49
0
from Player2 import *
from Interaction import *
from drawPlatforms import *
from Player import *
from LevelBackground import *
from Menu import *
from Level import *


from pygame import *

mixer.init()

from pygame import *

player1 = Player2(Vector(400, 400), "https://i.imgur.com/2cnk4Yx.png", 496, 1160, 10, 4, 'w', 'a', 's', 'd', 'up',
                  'left', 'right', 10, 3)
platforms = drawPlatforms("hard", 7)
lv1 = LevelBackground('https://i.imgur.com/Q7tBgIc.png')

interactions = []
addedInteractions = False


def draw(canvas):
    global interactions, addedInteractions
    lv1.update(canvas)
    platforms.draw(canvas)

    if not addedInteractions:
        for i in range(len(platforms.getCoords())):
Esempio n. 50
0
 def testCircleException(self):
     c = Vector.Vector([0, 0])
     r = -1
     self.assertRaisesRegex(Exception, "Radius less than zero",
                            Circle.Circle, c, r)
Esempio n. 51
0
 def __init__(self, newPosit,newN, newMaterial, objNum, t):
     self.locationVector = Vector(newPosit.x, newPosit.y, newPosit.z)
     self.n = newN
     self.material = newMaterial
     self.objNum = objNum
     self.t = t
Esempio n. 52
0
 def proyVec(self, proy):
     p = self.scale(proy / (proy - self.w))
     return v3d.Vector3D(p.x, p.y, p.z)
Esempio n. 53
0
winWidth, winHeight = 700, 700

pygame.init()
win = pygame.display.set_mode((winWidth, winHeight))
pygame.display.set_caption("Simulator")

particles = []
f = Field.Field(0, 0, 700, 700)
for i in range(f.dim.x):
    for j in range(f.dim.y):
        x = i - 350
        y = j - 350
        dx = y / 30
        dy = -(x**2) / 2000
        f.setVectors(i, j, Vector.Vector(dx, dy))

for i in range(300):
    p = Particle.Particle(random.randint(300, 400), random.randint(300, 400),
                          0, 0, 5, (255, 0, 0), win)
    particles.append(p)

running = True
while running:
    pygame.time.delay(10)
    win.fill(0)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
Esempio n. 54
0
 def _minTime(self, sPoint, gPoint):
     return np.ceil(
         Vector.distance_between(sPoint, gPoint) / self._robot_speed)
Esempio n. 55
0
 def rebound(self):
     distance = Vector.getDis(self.pos, self.world.center)
     if distance > self.world.center_dis != 0:
         return self.seek(self.world.center)
     else:
         return Vector(0, 0)
Esempio n. 56
0
 def bounds(self):
     return Vector(width, height)
Esempio n. 57
0
import math
import matplotlib.pyplot as plt
import numpy as np
from Vector import *
from RK4 import RK4, evaluateODE

M1 = 1.899 * 10**29; M2 = 1.989 * 10**30; G = 6.6742 * 10**(-11);
R = 778.3 * 10**9; T = 3.743 * 10**8;
r1 = Vector([M2 * R / (M1 + M2), 0, 0]); r2 = Vector([-M1 * R / (M1 + M2), 0, 0]);
O = math.sqrt(G * (M1 + M2) / (R**3))
alpha = math.pi / 8
rInit = R * Vector([(M2 - M1)/(M1 + M2) * math.cos(alpha), math.sin(alpha), 0])

def func(vec, t):
    r = Vector([vec[0], vec[2], 0])
    acc = -G*M1/Vector.magnitude(r-r1)**3 * (r-r1) - G*M2/Vector.magnitude(r-r2)**3 * (r-r2) + 2*O*Vector([vec[3], -vec[1], 0]) + O**2 * r
    return Vector([vec[1], acc[0], vec[3], acc[1]])

N = 2*T; h = T / 1000;
xList = []; yList = [];
vecInit = Vector([rInit[0], 0, rInit[1], 0])
vecList = evaluateODE(vecInit, h, func, N)
for v in vecList:
    xList.append(v[0]); yList.append(v[2]);

plt.plot(xList, yList); plt.xlabel("X"); plt.ylabel("Y"); plt.show();
Esempio n. 58
0
from Vector import *
v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2
Esempio n. 59
0
def func(vec, t):
    r = Vector([vec[0], vec[2], 0])
    acc = -G*M1/Vector.magnitude(r-r1)**3 * (r-r1) - G*M2/Vector.magnitude(r-r2)**3 * (r-r2) + 2*O*Vector([vec[3], -vec[1], 0]) + O**2 * r
    return Vector([vec[1], acc[0], vec[3], acc[1]])
Esempio n. 60
0
 def __init__(self, pos, heading, color):
     self.pos = Vector().set(pos)
     self.heading = Vector().set(heading)
     self.color = Vector().set(color)