def setNextPositionPerlin(self, *args, **kwargs): self.updateFunction = self.updatePerlin if('slow' in args): self.currentSpeedLimit = StewartPlatform.SERVO_SPEED_LIMIT/2 else: self.currentSpeedLimit = StewartPlatform.SERVO_SPEED_LIMIT*2 t = (time()-StewartPlatform.INIT_TIME) * StewartPlatform.PERLIN_TIME_SCALE (x,y,z) = self.currentPosition.getTranslationAsList() # direction u = snoise4(x*StewartPlatform.PERLIN_POSITION_SCALE + 1*StewartPlatform.PERLIN_PHASE, y*StewartPlatform.PERLIN_POSITION_SCALE + 1*StewartPlatform.PERLIN_PHASE, z*StewartPlatform.PERLIN_POSITION_SCALE + 1*StewartPlatform.PERLIN_PHASE, t + 1*StewartPlatform.PERLIN_PHASE) v = snoise4(x*StewartPlatform.PERLIN_POSITION_SCALE + 2*StewartPlatform.PERLIN_PHASE, y*StewartPlatform.PERLIN_POSITION_SCALE + 2*StewartPlatform.PERLIN_PHASE, z*StewartPlatform.PERLIN_POSITION_SCALE + 2*StewartPlatform.PERLIN_PHASE, t + 2*StewartPlatform.PERLIN_PHASE) w = snoise4(x*StewartPlatform.PERLIN_POSITION_SCALE + 3*StewartPlatform.PERLIN_PHASE, y*StewartPlatform.PERLIN_POSITION_SCALE + 3*StewartPlatform.PERLIN_PHASE, z*StewartPlatform.PERLIN_POSITION_SCALE + 3*StewartPlatform.PERLIN_PHASE, t + 3*StewartPlatform.PERLIN_PHASE) #magnitude thisSpeedScale = StewartPlatform.PERLIN_SPEED_SCALE/3 if ('slow' in args) else StewartPlatform.PERLIN_SPEED_SCALE speed = min(StewartPlatform.PERLIN_MAX_SPEED, max(StewartPlatform.PERLIN_MIN_SPEED, thisSpeedScale*(snoise4(u,v,w,t)*0.5+0.5))) # result deltaDistances = ( u*speed, v*speed, w*speed) deltaAngles = ( snoise2(v,t)*StewartPlatform.PERLIN_ANGLE_SCALE, snoise2(w,t)*StewartPlatform.PERLIN_ANGLE_SCALE, snoise2(u,t)*StewartPlatform.PERLIN_ANGLE_SCALE) # pick new valid position translateArg = kwargs.get('translate', '') rotateArg = kwargs.get('rotate', '') done = False while not done: translation = Vector3( deltaDistances[0] if 'x' in translateArg else 0, deltaDistances[1] if 'y' in translateArg else 0, deltaDistances[2] if 'z' in translateArg else 0) + self.currentPosition.translation translation.constrain(-StewartPlatform.PERLIN_DISTANCE_LIMIT, StewartPlatform.PERLIN_DISTANCE_LIMIT) rotation = Vector3( deltaAngles[0] if 'x' in rotateArg else 0, deltaAngles[1] if 'y' in rotateArg else 0, deltaAngles[2] if 'z' in rotateArg else 0) + self.currentPosition.rotation rotation.constrain(-StewartPlatform.PERLIN_ANGLE_LIMIT, StewartPlatform.PERLIN_ANGLE_LIMIT) done = self.setTargetAnglesSuccessfully(translation, rotation) deltaDistances = map(lambda x:0.9*x, deltaDistances) deltaAngles = map(lambda x:0.9*x, deltaAngles)
def find_closest_sprite(x,y): base_vector = Vector3(1,0,0) sprite_vector = Vector3(x,y,0).normalise() angle = (base_vector.dot(sprite_vector)) angle = math.acos(angle) angle = angle * 360.0 / (2 * math.pi) angle = int(angle) print(angle) if is_almost_equal(angle, 135, angle_fuzziness) or is_almost_equal(angle, 135 + 180, angle_fuzziness): return 0 if is_almost_equal(angle, 112, angle_fuzziness) or is_almost_equal(angle, 112 + 180, angle_fuzziness): return 1 if is_almost_equal(angle, 90, angle_fuzziness) or is_almost_equal(angle, 270, angle_fuzziness): return 2 if is_almost_equal(angle, 67, angle_fuzziness) or is_almost_equal(angle, 67 + 180, angle_fuzziness): return 3 if is_almost_equal(angle, 45, angle_fuzziness) or is_almost_equal(angle, 45 + 180, angle_fuzziness): return 4 if is_almost_equal(angle, 22, angle_fuzziness) or is_almost_equal(angle, 22 + 180, angle_fuzziness): return 5 if is_almost_equal(angle, 0, angle_fuzziness) or is_almost_equal(angle, 180, angle_fuzziness): return 6 if is_almost_equal(angle, 180 - 22, angle_fuzziness) or is_almost_equal(angle, 360 - 22, angle_fuzziness): return 6 return -1
def testAgainstBruteForceIntegration(self): '''Make sure our numerical integrator is doing a decent job at estimating arc length''' self.spline = CatmullRom([ Vector3(0, 0, 0), Vector3(1, 5, 0), Vector3(2, -3, 0), Vector3(3, 0, 0) ]) seg = 0 u1 = 0 u2 = 1 gaussResult = self.spline.arcLength(seg, u1, u2) # Let's use Brute Force n = 1000 dt = 1.0 / n L = 0 t = 0 for i in range(0, n): L += self.spline.velocity(seg, t).length() * dt t += dt # within a millimeter self.assertAlmostEqual(gaussResult, L, 3)
def setNextPositionScan(self, *args): self.updateFunction = self.updateLinear if('slow' in args): self.currentSpeedLimit = StewartPlatform.SERVO_SPEED_LIMIT/10 else: self.currentSpeedLimit = StewartPlatform.SERVO_SPEED_LIMIT/5 # pan actually means rotate around y-axis # and tilt means rotate around x-axis deltaAngles = (0,StewartPlatform.MOVE_SHORT_ANGLE/12*self.currentScanDirection[1],0) if(abs(self.currentPosition.rotation.y + deltaAngles[1]) > StewartPlatform.MOVE_LONG_ANGLE/3): self.currentScanDirection[1] *= -1 deltaAngles = (StewartPlatform.MOVE_SHORT_ANGLE/4*self.currentScanDirection[0],0,0) if(abs(self.currentPosition.rotation.x + deltaAngles[0]) > StewartPlatform.MOVE_LONG_ANGLE/2): self.currentScanDirection[0] *= -1 deltaAngles = (0,StewartPlatform.MOVE_SHORT_ANGLE/12*self.currentScanDirection[1],0) # move platform slightly closer to its initial height currentTranslation = self.currentPosition.translation translation = Vector3(currentTranslation.x, currentTranslation.y, currentTranslation.z*0.9) done = False while not done: rotation = Vector3(deltaAngles[0], deltaAngles[1], deltaAngles[2]) + self.currentPosition.rotation done = self.setTargetAnglesSuccessfully(translation, rotation) deltaAngles = map(lambda x:uniform(0.666,0.8)*x, deltaAngles)
def get(self, t, scale): t = float(scale * t) x_basis = self.p1 - self.p0 y_basis = x_basis.length() * Vector3.cross(x_basis, Vector3.k()).normalize() basis = Mat2x2.fromvectors( x_basis, y_basis ) transformed_v0 = (basis * self.v0).normalize() transformed_v1 = (basis * self.v1).normalize() slope_0 = transformed_v0.y / transformed_v0.x slope_1 = transformed_v1.y / transformed_v1.x spline = Vector3( t, (self.H2(t) * slope_0) + (self.H3(t) * slope_1) ) # f.write("{},{}\n".format( # spline.x, spline.y # )) spline_der = Vector3( scale, (self.d_H2(t, scale) * slope_0) + (self.d_H3(t, scale) * slope_1) ) return ((basis * spline) + self.p0, (basis * spline_der))
def ray_from_ndc(self, pos): """Retrieves a ray (origin, direction) corresponding to the given position on screen. This function takes the coordinates as NDC (normalized device coordinates), in which the lower-left corner of the screen corresponds to (-1,-1) and the upper-right corresponds to (1,1). For example, to convert mouse coordinates to NDC, you could do something like: >>> mouse_pos = pygame.mouse.get_pos() >>> mouse_pos = ((mouse_pos[0] / res_x) * 2 - 1, (mouse_pos[1] / res_y) * 2 - 1) >>> origin, dir = camera.RayFromNDC(mouse_pos) Arguments: pos {2-tuple} -- Screen position in NDC (normalized device coordinates) Returns: Vector3, Vector3 - Origin and direction of the ray corresponding to that screen positions """ vpos = Vector3(pos[0], pos[1], self.near_plane) vpos.x = vpos.x * self.res_x * 0.5 vpos.y = -vpos.y * self.res_y * 0.5 inv_view_proj_matrix = self.get_camera_matrix( ) * self.get_projection_matrix() inv_view_proj_matrix.invert() direction = inv_view_proj_matrix.posmultiply_v3(vpos, 1) direction = Vector3(direction.x, direction.y, direction.z).normalized() return self.position + direction * self.near_plane, direction
def __init__(self, name, height=DEFAULT_HEIGHT, width=DEFAULT_WIDTH, depth=DEFAULT_DEPTH, start_pos=Vector3(0, 0, 0), color=Color(0, 1, 0, 1)): self.height = height self.width = width self.depth = depth self.name = name self.position = start_pos self.rotation = Quaternion.identity() self.scale = Vector3(1, 1, 1) if (height == self.DEFAULT_HEIGHT) and ( width == self.DEFAULT_WIDTH) and (depth == self.DEFAULT_DEPTH): self.mesh = self.BLOCK_MESH else: self.mesh = Mesh.create_cube((self.width, self.height, self.depth)) self.material = Material(color, "Block Material") self.children = [] self.my_collider = AABB_Collider( Vector3(self.width, self.height, self.depth))
def __init__(self, num_of_particles, position, lifetime, velocity=Vector3(0, -100, 0), acceleration=Vector3(0, 50, 0), x_angle=100, z_angle=100, spawn_rate=5): self.num_of_particles = num_of_particles self.position = position self.velocity = velocity self.acceleration = acceleration self.x_angle = x_angle self.z_angle = z_angle self.lifetime = lifetime self.spawn_rate = spawn_rate self.particles = [] for _ in range(num_of_particles): particle = PhysicsParticle(lifetime, velocity=velocity, acceleration=acceleration, x_angle=x_angle, z_angle=z_angle, position=position) self.particles.append(particle)
def generateSphere(n, r, color): """ this will generate a sphere sitting in O and divide as mentioned """ vertexes = [] triangles = [] for d in range(n + 1): yb = 2 * r * d / n - r for i in range(n): alpha = 2 * pi * i / n rprime = sqrt(r * r - yb * yb) xb = rprime * cos(alpha) zb = rprime * sin(alpha) vertexes.append(Vector3(xb, yb, zb)) for i in range(n): start = i * n for j in range(n - 1): a = start + j b = a + 1 c = a + n d = c + 1 triangles.append(Triangle(a, d, b, color)) triangles.append(Triangle(a, c, d, color)) return Model(vertexes, triangles, Vector3(0, 0, 0), r)
def __init__(self): if Missile.missile_mesh is None: Missile.missile_mesh = Missile.create_missile_mesh() Missile.missile_material = Material(Color(1, 0, 0, 1), "MissileMaterial") super().__init__("Missile") # Determine the spawn position. There's 33% chance it comes from the right, 33% that it # comes from behind the mountains, and 34% chance it comes from the left self.position = Vector3(0, random.uniform(0, 3), 12) r = random.uniform(0, 100) if r > 66: self.position.x = 7 self.rotation = Quaternion.AngleAxis(Vector3(0, 1, 0), math.radians(-90)) elif r > 33: self.position.y = -2 self.position.x = random.uniform(-4, 4) self.rotation = Quaternion.AngleAxis(Vector3(1, 0, 0), math.radians(-90)) else: self.position.x = -7 self.rotation = Quaternion.AngleAxis(Vector3(0, 1, 0), math.radians(90)) # Set the mesh and material of the missile self.mesh = Missile.missile_mesh self.material = Missile.missile_material # Sets the missile linear speed self.missile_speed = 2 # Sets the rotation speed (in radians per second) self.missile_rotation_speed = 0.75
def _manipulate(self, ent, amountx, amounty, lengthx, lengthy): if self.grabbed and self.grabbed_axis is not None: rightvec = Vector3(r.getCameraRight()) upvec = Vector3(r.getCameraUp()) ort = ent.placeable.Orientation euler = list((0, 0, 0)) if self.grabbed_axis == self.AXIS_GREEN: #rotate z-axis #print "green axis", self.grabbed_axis mov = amountx * 30 euler[2] += mov elif self.grabbed_axis == self.AXIS_BLUE: #rotate x-axis #print "blue axis", self.grabbed_axis mov = amountx * 30 euler[1] += mov elif self.grabbed_axis == self.AXIS_RED: #rotate y-axis #print "red axis", self.grabbed_axis mov = amounty * 30 euler[0] -= mov rotationQuat = list(euler_to_quat(euler)) ort.__imul__( Quat(rotationQuat[3], rotationQuat[0], rotationQuat[1], rotationQuat[2])) ent.placeable.Orientation = ort ent.network.Orientation = ort
def _manipulate(self, ent, amountx, amounty, lengthx, lengthy): if self.grabbed: qscale = ent.placeable.Scale scale = list((qscale.x(), qscale.y(), qscale.z())) rightvec = Vector3(r.getCameraRight()) upvec = Vector3(r.getCameraUp()) if self.grabbed_axis == self.AXIS_BLUE: mov = lengthy scale[self.grabbed_axis] -= mov else: mov = lengthx div = abs(rightvec[self.grabbed_axis]) if div == 0: div = 0.01 #not the best of ideas but... mov *= rightvec[self.grabbed_axis] / div scale[self.grabbed_axis] += mov newscale = Vec(scale[0], scale[1], scale[2]) ent.placeable.Scale = newscale self.controller.updateSelectionBox(ent) qprim = ent.prim if qprim is not None: children = qprim.GetChildren() for child_id in children: child = r.getEntity(int(child_id)) child.placeable.Scale = newscale
def setUp(self): self.spline = CatmullRom([ Vector3(0, 0, 0), Vector3(1, 0, 0), Vector3(2, 0, 0), Vector3(3, 0, 0) ])
def rotate_yaw_pitch_row(eulers): # type: (Vector3) -> Matrix4 m = Matrix4.identity() # NOTE in zxy order m = glm.rotate(m, eulers.z, Vector3(0, 0, 1)) m = glm.rotate(m, eulers.x, Vector3(1, 0, 0)) m = glm.rotate(m, eulers.y, Vector3(0, 1, 0)) return m
def icosahedron(): vertices = [ v for p in [1, -1] for q in [tau, -tau] for v in [Vector3(p, q, 0), Vector3(q, 0, p), Vector3(0, p, q)] ] return tiling3_convex_hull(dict(zip(vertices, range(12))))
def tetrahedron(): d = { Vector3(-1, -1, -1): 1, Vector3(-1, 1, 1): 2, Vector3(1, -1, 1): 3, Vector3(1, 1, -1): 4 } return tiling3_convex_hull(d)
def setUp(self): # 1 meter long spline self.spline = CatmullRom([ Vector3(0, 0, 0), Vector3(1, 0, 0), Vector3(2, 0, 0), Vector3(3, 0, 0) ])
def test_mul(self): v1 = Vector3(1, 2, 3) v2 = Vector3(4, 5, 6) self.assertEqual(3 * v1, (3, 6, 9)) self.assertEqual(v1 * 3, (3, 6, 9)) self.assertEqual((3, 3, 3) * v1, (3, 6, 9)) self.assertEqual(v1 * (3, 3, 3), (3, 6, 9)) v1 *= 2 self.assertEqual(v1, (2, 4, 6))
def test_div(self): v1 = Vector3(1, 2, 3) v2 = Vector3(4, 5, 6) # self.assertEqual(3 / v1, (3., 3. / 2, 1.)) self.assertEqual(v1 / 3, (1. / 3, 2 / 3., 3 / 3.)) # self.assertEqual((3, 3, 3) / v1, (3. / 1., 3. / 2., 3. / 3.)) self.assertEqual(v1 / (3, 3, 3), (1. / 3, 2 / 3., 3 / 3.)) v1 /= 2 self.assertEqual(v1, (.5, 1., 1.5))
def __init__(self): super(Camera, self).__init__() self.aperture = 90.0 self.camera3dPosition = Vector3(0.0, 0.0, 10.0) self.view = Vector3(0.0, 0.0, -10.0) self.up = Vector3(0.0, 1.0, 0.0) self.zNearClip = 0.001 self.zFarClip = 200.0
def testAddCancel(self): """ Test adding a vector and its inverse """ loc = LocationGlobalRelative(-45.6549814, 65.216548, 45.25641) vec = Vector3(85.6, -23.4, 3.4) vecInv = Vector3(-85.6, 23.4, -3.4) newloc = location_helpers.addVectorToLocation(loc, vec) newloc = location_helpers.addVectorToLocation(newloc, vecInv) dist = location_helpers.getDistanceFromPoints3d(loc, newloc) self.assertTrue(abs(dist) < ERROR)
def setNextPositionLinear(self, *args, **kwargs): self.updateFunction = self.updateLinear if ('repeat' in args): if ('slow' in args): self.currentSpeedLimit = StewartPlatform.SERVO_SPEED_LIMIT / 2 elif ('fast' in args): self.currentSpeedLimit = StewartPlatform.SERVO_SPEED_LIMIT self.setTargetAnglesSuccessfully(self.lastPosition.translation, self.lastPosition.rotation) else: if ('slow' in args): self.currentSpeedLimit = StewartPlatform.SERVO_SPEED_LIMIT / 2 else: self.currentSpeedLimit = StewartPlatform.SERVO_SPEED_LIMIT # pick new valid position translateArg = kwargs.get('translate', '') rotateArg = kwargs.get('rotate', '') deltaDistances = [0] * 3 deltaAngles = [0] * 3 if (('short' in args) or ('near' in args)): # randomly move towards -MOVE_SHORT_ or +MOVE_SHORT_ # makes a list by picking -MOVE_SHORT_ or +MOVE_SHORT_ 3 times deltaDistances = map(lambda x: choice([-1, 1]) * x, [StewartPlatform.MOVE_SHORT_DISTANCE] * 3) deltaAngles = map(lambda x: choice([-1, 1]) * x, [StewartPlatform.MOVE_SHORT_ANGLE] * 3) else: # picks new potential long targets from current position deltaDistances = map( StewartPlatform.pickLongTargetValue( StewartPlatform.MOVE_LONG_DISTANCE), self.currentPosition.getTranslationAsList()) deltaAngles = map( StewartPlatform.pickLongTargetValue( StewartPlatform.MOVE_LONG_ANGLE), self.currentPosition.getRotationAsList()) done = False while not done: translation = Vector3( deltaDistances[0] if 'x' in translateArg else 0, deltaDistances[1] if 'y' in translateArg else 0, deltaDistances[2] if 'z' in translateArg else 0) + self.currentPosition.translation rotation = Vector3( deltaAngles[0] if 'x' in rotateArg else 0, deltaAngles[1] if 'y' in rotateArg else 0, deltaAngles[2] if 'z' in rotateArg else 0) + self.currentPosition.rotation done = self.setTargetAnglesSuccessfully(translation, rotation) deltaDistances = map(lambda x: uniform(0.666, 0.8) * x, deltaDistances) deltaAngles = map(lambda x: uniform(0.666, 0.8) * x, deltaAngles)
def _manipulate(self, ent, amountx, amounty, lengthx, lengthy): rightvec = Vector3(r.getCameraRight()) upvec = Vector3(r.getCameraUp()) changevec = (amountx * rightvec) - (amounty * upvec) qpos = ent.placeable.Position entpos = Vector3(qpos.x(), qpos.y(), qpos.z()) newpos = entpos + changevec newpos = Vec(newpos.x, newpos.y, newpos.z) ent.placeable.Position = newpos ent.network.Position = newpos
def periodic_copies(tiling3, bounding_box, periods=[Vector3(1,0,0), Vector3(0,1,0), Vector3(0,0,1)]): gen = LatticeSearcher(len(periods)) for n in gen: t1 = tiling3.translate(sum((u*c for (u,c) in zip(periods, n)), Vector3(0,0,0))) if t1.in_box(bounding_box): yield t1 else: gen.reject()
def trace_diffuse(self, ray, scene): self.__scene = scene hit_object, hit_point, hit_normal = self.__intersect(ray) if hit_object is None: return Vector3(0.3, 0.3, 0.3) # horizon traced_color = Vector3() if hit_object.material.is_diffuse: traced_color = self.__trace_diffuse(hit_object, hit_point, hit_normal) return traced_color
def restrict43(t): """ Given a Tiling4, produce the Tiling3 corresponding to the cross-section consisting of the hyperplane with z coordinate = 0. For example, if t is a tiling of hypercubes, translated a little, then the result will be a cubic tiling. If you want a different hyperplane cross-section, you've got to rotate and translate the tiling first. For now, it complains if any vertices have z = 0. Of course, this should be a measure-zero event, and can be avoided by small translations. This makes the algorithm much simpler: edges in the input produce vertices in the output; faces in the input produce edges in the output, volumes in the input produce faces in the output, and hypervolumes in the input produce volumes in the output. """ for (v, x) in t.vertices.items(): if v.z == 0: raise ValueError("Vertex %s lies in cell z=0" % (v, )) # Check Cell is the right word. newv = {} for (e, l) in t.edges.items(): (v1, v2) = e if v2.z < 0 < v1.z: (v1, v2) = (v2, v1) if v1.z < 0 < v2.z: # If the edge passes through the plane z=0, then the # result will contain a vertex lying at the point of # intersection. u1 = Vector3(v1.w, v1.x, v1.y) u2 = Vector3(v2.w, v2.x, v2.y) newv[e] = ((u1 * (v2.z) - u2 * (v1.z)) / (v2.z - v1.z), l) newe = {} for (f, x) in t.faces.items(): e = frozenset(newv[e1][0] for e1 in f if e1 in newv) if e: newe[f] = (e, x) newf = {} for (g, x) in t.volumes.items(): f = frozenset(newe[f1][0] for f1 in g if f1 in newe) if f: newf[g] = (f, x) newg = {} for (h, x) in t.hypervolumes.items(): g = frozenset(newf[g1][0] for g1 in h if g1 in newf) if g: newg[h] = (g, x) return Tiling3(newv.values(), newe.values(), newf.values(), newg.values())
def dodecahedron(): vertices1 = [ Vector3(x, y, z) for x in [-1, 1] for y in [-1, 1] for z in [-1, 1] ] vertices2 = [ v for p in [tau, -tau] for q in [tau.conj(), -tau.conj()] for v in [Vector3(p, q, 0), Vector3(q, 0, p), Vector3(0, p, q)] ] return tiling3_convex_hull(dict(zip(vertices1 + vertices2, range(20))))
def __init__(self, mass=1, position=Vector3(), velocity=Vector3(), rotation=Vector3(), acceleration=Vector3()): self.mass = mass self.position = position self.velocity = velocity self.rotation = rotation self.acceleration = acceleration
def testAcceleration(self): '''For an evenly spaced straight-line spline, test that acceleration is zero''' seg = 0 u = 0 ddq = self.spline.acceleration(seg, u) self.assertEqual(ddq, Vector3(0.0, 0.0, 0.0)) u = 0.5 ddq = self.spline.acceleration(seg, u) self.assertEqual(ddq, Vector3(0.0, 0.0, 0.0)) u = 1.0 ddq = self.spline.acceleration(seg, u) self.assertEqual(ddq, Vector3(0.0, 0.0, 0.0))
def __init__(self, surface_color=Vector3(), emission_color=Vector3(), reflectivity=0.0, transparency=0.0, ior=1.0): """Creates a new material""" self.__surface_color = surface_color self.__emission_color = emission_color self.__reflectivity = reflectivity self.__transparency = transparency self.__ior = ior