def __init__( self , fovy , ratio , near , far , robot_files ) : self.fovy = fovy self.near = near self.far = far self.ratio = ratio self.camera = None self.plane = Plane( (2,2) ) self.wall = Plane( (20,10) ) self.mw = tr.rotation_matrix( -m.pi / 2.0 , (1,0,0) ) self.mw = np.dot( self.mw , tr.translation_matrix( (0,3,0) ) ) self.robot = Robot( robot_files ) self.x = 0.0 self.last_time = timer() self.plane_alpha = 65.0 / 180.0 * m.pi self.lpos = [ 1 ,-1 , 0 ] self._make_plane_matrix() self.draw_robot = True self.draw_sparks = True self.draw_front = False self.draw_back = False
def __init__(self, center = [0,0,0], normal = [0,0,1], radius = 1): ''' Constructor Parameters: center: center location of circle normal: surface normal of circle radius: radius of circle ''' # normal should be length 1 normal = normal/norm(normal) # create rectangular dimensions if normal[0] == 0 and normal[2] == 0: # normal is in y direction sign = normal[1] # 1 or -1 ax1 = sign*np.array((0,0,1),dtf) ax2 = sign*np.array((0,1,0),dtf) else: ax1 = np.cross([0,1,0],normal) # parallel to xz-plane ax2 = np.cross(normal,ax1) Plane.__init__(self,origin=center,ax1=ax1,ax2=ax2) self.center = np.array(center,dtf) self.normal = np.array(normal,dtf) self.radius = radius
def test_plane_is_parallel(): """Test if a plane is parallel""" plane1 = Plane(Vector([2, 3, 4]), 6) plane2 = Plane(Vector([2, 3, 4]), 1) assert plane1.is_parallel(plane2) is True assert plane1.is_coincidence(plane2) is False
def test_plane_is_coincidence_scale(): """Test if a plane is a coincidece""" plane1 = Plane(Vector([2, 3, 4]), 1) plane2 = Plane(Vector([4, 6, 8]), 2) assert plane1.is_parallel(plane2) is True assert plane1.is_coincidence(plane2) is True assert plane1.plane_relationship(plane2) == 'planes are coincidental'
def __init__(self, center=[0, 0, -10], width=10.302, # 2*5.151 (max radius of default module) height=10.302, normal=[0, 0, 1], type='atinf', color=[1, 1, 1], pixels=None, spectrum=None ): ''' Constructor Parameters: center: the center location of the source width: the width of the projection rectangle (atinf or nonpoint) height: the height of the projection rectangle (atinf or nonpoint) normal: direction the projection rectangle is facing type: 'atinf', 'point', or 'nonpoint' color: color of projected rays pixels: optional numpy array of pixel colors (W x H x 3) spectrum: optional numpy array (2xN) of energy spectrum ''' # normal should be length 1 normal = normal / norm(normal) # check type if type not in ['atinf', 'point', 'nonpoint']: raise ValueError('invalid source type') # check dims if type is not 'point' and (width <= 0 or height <= 0): raise ValueError('atinf or nonpoint source must have positive area') # create rectangular dimensions if normal[0] == 0 and normal[2] == 0: # normal is in y direction sign = normal[1] # 1 or -1 ax1 = sign * np.array((0, 0, width), dt) ax2 = sign * np.array((0, height, 0), dt) else: ax1 = np.cross([0, 1, 0], normal) # parallel to xz-plane ax2 = height * np.cross(normal, ax1) ax1 *= width # calc origin origin = np.array(center) - (0.5 * ax1 + 0.5 * ax2) # instantiate Plane.__init__(self, origin, ax1, ax2) self.center = np.array(center, dt) self.type = type self.color = np.array(color, np.dtype('f4')) self.pixels = pixels self._spectrum = spectrum self._maximum_energy = 1000 # this is the maximum energy considered
def __init__(self, center=[0, 0, 230], width=2, height=2, normal=[0, 0, 1], reso=[256, 256], pixels=None, freqs=None, ): ''' Constructor Parameters: center: the center location of the source width: the width of the projection rectangle height: the height of the projection rectangle normal: direction the projection rectangle is facing reso: resolution of pixels (W,H) pixels: optional numpy array to hold pixel colors (W x H x 3) freqs: optional array to count the number of times a pixel is hit (W x H) ''' # normal should be length 1 normal = normal / norm(normal) # create rectangular dimensions if normal[0] == 0 and normal[2] == 0: # normal is in y direction sign = normal[1] # 1 or -1 ax1 = sign * np.array((0, 0, width), dtf) ax2 = sign * np.array((0, height, 0), dtf) else: ax1 = np.cross([0, 1, 0], normal) # parallel to xz-plane ax2 = height * np.cross(normal, ax1) ax1 *= width # calc origin origin = np.array(center) - (0.5 * ax1 + 0.5 * ax2) # instantiate Plane.__init__(self, origin, ax1, ax2) self.center = np.array(center, dtf) self.reso = reso self.pixels = pixels self.freqs = freqs self.rays = [] # bring in pixels if pixels is None: self._initDetectorImage() elif freqs is None: raise ValueError('must pass freqs when passing pixels') elif pixels.shape[0:2] != freqs.shape: raise ValueError('pixels and freqs arrays do not correspond')
def test_plane_insertion(self): """ Tests the insertion of ids in plane """ my_plane = Plane(x_size=10, y_size=10) my_plane.insert_node(Node(node_id=1), Location(3, 4)) my_plane.insert_node(Node(node_id=2), Location(3, 5)) my_plane.insert_node(Node(node_id=3), Location(1, 2)) self.assert_("1" in my_plane.all_node_ids) self.assert_("2" in my_plane.all_node_ids) self.assert_("3" in my_plane.all_node_ids)
class PlaneSprite(pygame.sprite.Sprite): """moves a clenched fist on the screen, following the mouse""" def __init__(self): pygame.sprite.Sprite.__init__(self) #call Sprite initializer self.image, self.rect = load_image('plane_low.png', -1) self.plane = Plane(randint(0, DISPLAY_WIDTH), randint(0, DISPLAY_HEIGHT), randint(MIN_ALTITUDE, MAX_ALTITUDE)) # self.plane.setCourse(randint(496, 500), 400, 600, SPEED) self.plane.setCourse(randint(0, DISPLAY_WIDTH), randint(0, DISPLAY_HEIGHT), randint(MIN_ALTITUDE, MAX_ALTITUDE), SPEED) self.originalImage = self.image def update(self): self.image = self.originalImage self.rect = self.image.get_rect() # Setting the position and saving it before transformations self.plane.flyAway() self.rect.center = self.plane.int2Dpos() center = self.rect.center # Scale down the icon scale = PLANE_SIZE / self.rect.width # Calculate heading and rotate the icon accordingly if self.plane.velocity.x == 0: heading = 0 else: heading = math.degrees(math.atan(-self.plane.velocity.y/self.plane.velocity.x)) if self.plane.velocity.x < 0: heading += 180 self.image = pygame.transform.rotozoom(self.image, heading, scale) # Restoring the position after transformations self.rect = self.image.get_rect() self.rect.center = center white = pygame.Surface(self.rect.size) white.fill(Color('white')) self.image.blit(white, (0, 0), None, BLEND_MAX) # Change the plane's color according to its height heightToColor = int(((self.plane.position.z - MIN_ALTITUDE) / (MAX_ALTITUDE - MIN_ALTITUDE)) * 255) if heightToColor > 255: heightToColor = 255 if heightToColor < 0: heightToColor = 0 heightColor = pygame.Surface(self.rect.size) heightColor.fill((heightToColor, heightToColor, heightToColor)) self.image.blit(heightColor, (0, 0), None, BLEND_MIN)
def newPlane(self, icao): plane = Plane() plane.icao = icao query = Aircraft.query(Aircraft.icao == icao).fetch() if (query == []): tmp = Aircraft() tmp.icao = icao tmp.put() del tmp del query else: del query self.pushPlane(icao, plane) return plane
def findRotationScaleTranslation(self): # I use the technique described in http://igl.ethz.ch/projects/ARAP/svd_rot.pdf # to calculate the rotation matrix # We begin by assembling both pointclouds pCloudA = [] pCloudB = [] for signal in self.signals: for via in signal.vias: for dataPoint in via.calibrationData: tipPosition = dataPoint[2] tipPositionOnPCBPlane = self.plane.planeRepresentationForSensorPoint(tipPosition) pCloudA.append(np.array([via.x,via.y])) pCloudB.append(np.array(tipPositionOnPCBPlane)) f = open('pointcloud.dat','w') logCloudA = [] logCloudB = [] for i in range(len(pCloudA)): logCloudA.append([pCloudA[i][0],pCloudA[i][1]]) logCloudB.append([pCloudB[i][0],pCloudB[i][1]]) t = {'A':logCloudA,'B':logCloudB} f.write(json.dumps(t)) f.write('\n') f.close() rotMat, centroidA, centroidB ,scaleAB = Plane.findRotationTranslationScaleForPointClouds(pCloudA,pCloudB) self.rotMat = rotMat self.centroidA = centroidA self.centroidB = centroidB self.scaleAB = scaleAB self.calibrated = True
def getplanes(lock): c_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM); c_socket.connect(('localhost',30003)); for line in c_socket.makefile('r'): parts=[x.strip() for x in line.split(',')] if parts[0] == 'MSG': id = parts[4] lock.acquire() if id in planes: plane =planes[id] else: plane = Plane(parts[4], datetime.utcnow()) planes[id]=plane plane.update(parts) lock.release()
class TestPlaneBuilder(unittest.TestCase): def setUp(self): self.node_a = Node(node_id="1") self.node_b = Node(node_id="2") self.node_c = Node(node_id="3") self.few_nodes = {} self.many_nodes = {} few_nodes_list = Node.generate_nodes(3, Node, node_parameters={}, protocol_manager=None) for node in few_nodes_list: self.few_nodes[node.id] = node many_nodes_list = Node.generate_nodes(300, Node, node_parameters={}, protocol_manager=None) for node in many_nodes_list: self.many_nodes[node.id] = node self.plane_1 = Plane(10, 20) self.plane_2 = Plane(30, 30) def test_small_plane_builder(self): plane_builders.degree_plane_builder(self.plane_1, 2, 4, self.few_nodes) self.assertEqual(len(self.plane_1.all_node_ids), 3) def test_bigger_plane_builder(self): plane_builders.degree_plane_builder(self.plane_2, 2, 2, self.many_nodes) self.assertEqual(len(self.plane_2.all_node_ids), 300) def test_square_plane_builder(self): plane_builders.square_builder(self.plane_2, 2, 2, self.many_nodes) self.assertEqual(len(self.plane_2.all_node_ids), 300) self.assert_(self.plane_2.get_node(Location(0,0)))
def initialize(self): rect = Rectangle() rect.bottomLeft = self.intersection(self.ray(0, 0)) rect.topLeft = self.intersection(self.ray(0, self.image['height'])) rect.topRight = self.intersection(self.ray(self.image['width'], self.image['height'])) rect.bottomRight = self.intersection(self.ray(self.image['width'], 0.0)) self.pyramid = Pyramid(self.position, rect) self.plane = Plane(rect, self.image)
def __init__(self, simulation_parameters): """ Constructor. simulation_parameters - The parameters to be used to run this simulation """ self.type_of_nodes = simulation_parameters.config_p['type_of_nodes'] self._max_cycles = simulation_parameters.config_p['max_cycles'] self.number_messages_out = 0 self.number_messages_in = 0 self.number_asynchronous_events = 0 self.number_simulation_events = 0 self.all_nodes = {} self.time = 0 self.protocol_manager = \ simulation_parameters.config_p['protocol_manager'](protocol_arguments=simulation_parameters.protocol_p) self.event_broker = EventBroker() self.message_broker = MessageBroker() node_parameters = simulation_parameters.node_p type_of_nodes = simulation_parameters.config_p['type_of_nodes'] events_to_launch = simulation_parameters.config_p['events'] # If the simulator is generating the plane if not 'scenario_file' in simulation_parameters.plane_p: generated_nodes = Node.generate_nodes(number_to_generate=simulation_parameters.plane_p['number_of_nodes'], \ type_of_nodes=type_of_nodes, node_parameters=node_parameters, \ protocol_manager=self.protocol_manager) for node in generated_nodes: self.all_nodes[node.id] = node self.plane = Plane.generate_plane(all_nodes=self.all_nodes, plane_parameters=simulation_parameters.plane_p) # If the simulator is loading the plane from a file else: (self.all_nodes, self.plane) = Plane.load_plane(plane_parameters=simulation_parameters.plane_p, \ node_parameters=simulation_parameters.node_p, \ type_of_nodes=self.type_of_nodes, \ protocol_manager=self.protocol_manager) #Now putt the events to launch in the event broker for event in events_to_launch: self.event_broker.add_asynchronous_event(event)
def showplanes(win, lock): plane = Plane('abcdef',datetime.utcnow()) while True: time.sleep(.500) row=2 win.erase() plane.showheader(win) lock.acquire() for id in sorted(planes, key=planes.__getitem__): planes[id].showincurses(win, row) row=row+1 now=str(datetime.utcnow()) win.addstr(rows-1,cols-5-len(now),now) win.refresh() removeplanes() lock.release()
def __init__(self): pygame.sprite.Sprite.__init__(self) #call Sprite initializer self.image, self.rect = load_image('plane_low.png', -1) self.plane = Plane(randint(0, DISPLAY_WIDTH), randint(0, DISPLAY_HEIGHT), randint(MIN_ALTITUDE, MAX_ALTITUDE)) # self.plane.setCourse(randint(496, 500), 400, 600, SPEED) self.plane.setCourse(randint(0, DISPLAY_WIDTH), randint(0, DISPLAY_HEIGHT), randint(MIN_ALTITUDE, MAX_ALTITUDE), SPEED) self.originalImage = self.image
def test_problems(self): """ :type self: object """ p1 = Plane(Vector([-0.412, 3.806, 0.728]), -3.46) p2 = Plane(Vector([1.03, -9.515, -1.82]), 8.65) self.assertEqual(p1, p2) p1 = Plane(Vector([2.611, 5.528, 0.283]), 4.6) p2 = Plane(Vector([7.715, 8.306, 5.342]), 3.76) self.assertFalse(p1.is_parallel_to(p2)) p1 = Plane(Vector([-7.926, 8.625, -7.212]), -7.952) p2 = Plane(Vector([-2.642, 2.875, -2.404]), -2.443) self.assertNotEqual(p1, p2) self.assertTrue(p1.is_parallel_to(p2))
def setUp(self): self.test_plane = Plane(x_size=5, y_size=10) node_a = Node(node_id=1) node_b = Node(node_id=2) node_c = Node(node_id=3) self.all_nodes = {1:node_a, 2:node_b, 3:node_c} self.test_plane.insert_node(node_a, Location(0, 0)) self.test_plane.insert_node(node_b, Location(2, 1)) self.test_plane.insert_node(node_c, Location(1, 2))
class TestPlotPlane(unittest.TestCase): def setUp(self): self.test_plane = Plane(x_size=5, y_size=10) node_a = Node(node_id=1) node_b = Node(node_id=2) node_c = Node(node_id=3) self.all_nodes = {1:node_a, 2:node_b, 3:node_c} self.test_plane.insert_node(node_a, Location(0, 0)) self.test_plane.insert_node(node_b, Location(2, 1)) self.test_plane.insert_node(node_c, Location(1, 2)) def test_plot(self): """ Tests the removal of an existing node """ plot_plane.plot_plane(self.test_plane, self.all_nodes, 'unit_test_plot_plane')
def test_planes_in_3d(): """Quiz 8 plane functions""" plane1 = Plane(Vector([-0.412, 3.806, 0.728]), -3.46) plane2 = Plane(Vector([1.03, -9.515, -1.82]), 8.65) assert plane1.is_parallel(plane2) is True assert plane1.is_coincidence(plane2) is True assert plane1.plane_relationship(plane2) == ('planes are coincidental') plane3 = Plane(Vector([2.611, 5.528, 0.283]), 4.6) plane4 = Plane(Vector([7.715, 8.306, 5.342]), 3.76) assert plane3.is_parallel(plane4) is False assert plane3.plane_relationship(plane4) == ('planes are not parallel') plane5 = Plane(Vector([-7.926, 8.625, -7.212]), -7.952) plane6 = Plane(Vector([-2.642, 2.875, -2.404]), -2.443) assert plane5.is_parallel(plane6) is True assert plane5.plane_relationship(plane6) == ('planes are parallel')
def main(screen): curses.start_color() curses.init_pair(1,curses.COLOR_GREEN, curses.COLOR_BLUE) screen.refresh() c_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM); c_socket.connect(('localhost',30003)); win = curses.newwin(rows,cols,1,1) win.bkgd(curses.color_pair(1)) win.box() for line in c_socket.makefile('r'): #print line parts=[x.strip() for x in line.split(',')] if parts[0] == 'MSG': id = parts[4] if id in planes: plane =planes[id] else: plane = Plane(parts[4], datetime.utcnow()) planes[id]=plane plane.update(parts) removeplanes() row=2 win.erase() plane.showheader(win) for id in sorted(planes, key=planes.__getitem__): planes[id].showincurses(win, row) row=row+1 now=str(datetime.utcnow()) win.addstr(rows-1,cols-5-len(now),now) win.refresh()
def calibrate(self): # Calibration comes in three phases # Phase 1, Find the plane of the PCB # make a list of all data points print 'Calibrating...' print 'Finding PCB plane..' dataPoints = [] for i in self.signals: for j in i.vias: for k in j.calibrationData: dataPoints.append(k[2]) self.plane = Plane.leastSquaresFit(dataPoints) print self.plane self.plane.parameterize() #Now, we have the plane. We should find two axes on the plane self.findRotationScaleTranslation() self.calibrated = True
def setUp(self): self.node_a = Node(node_id="1") self.node_b = Node(node_id="2") self.node_c = Node(node_id="3") self.few_nodes = {} self.many_nodes = {} few_nodes_list = Node.generate_nodes(3, Node, node_parameters={}, protocol_manager=None) for node in few_nodes_list: self.few_nodes[node.id] = node many_nodes_list = Node.generate_nodes(300, Node, node_parameters={}, protocol_manager=None) for node in many_nodes_list: self.many_nodes[node.id] = node self.plane_1 = Plane(10, 20) self.plane_2 = Plane(30, 30)
class FeatureTestCase(unittest.TestCase): def setUp(self): self.plane = Plane() self.airport = Airport(20,[]) self.weather = MagicMock() def test_planes_can_land(self): self.plane.land(self.airport, self.weather) self.assertEqual(self.airport.planes,[self.plane]) def test_planes_can_take_off(self): self.plane.land(self.airport, self.weather) self.plane.take_off(self.airport, self.weather) self.assertEqual(self.airport.planes, [])
def test_bfg_draw_heat_map(self): all_nodes = {} # make all the nodes for i in xrange(50): node_a = BfgNode(node_id=str(i), protocol_manager=self.protocol_manager) all_nodes[str(i)] = node_a # make the plane import plane_builders from simulator import PlaneParameters plane_p = PlaneParameters(x_size = 10, y_size = 10, min_degree=1, max_degree=8, plane_builder_method=plane_builders.degree_plane_builder) plane = Plane.generate_plane(all_nodes=all_nodes, plane_parameters=plane_p) #make the protocol manager bfg_protocol = BfgProtocolManager({'origin_ids':["1", "2"], 'destiny_ids':["3"]}) #Make heat spread #TODO #Draw the map bfg_protocol.draw_heat_map("Final Heat", all_nodes, plane, '3')
def multiply_coefficient_and_row(self, coefficient, row): new_n= self[row].normal_vector.times_scalar(coefficient) new_k= self[row].constant_term*coefficient self[row]= Plane(normal_vector=new_n, constant_term= new_k) pass # add your code here
def __str__(self): ret = 'Linear System:\n' temp = ['Equation {}: {}'.format(i+1,p) for i,p in enumerate(self.planes)] ret += '\n'.join(temp) return ret class MyDecimal(Decimal): def is_near_zero(self, eps=1e-10): return abs(self) < eps p0 = Plane(normal_vector=Vector(['1','2','3']), constant_term='1') p1 = Plane(normal_vector=Vector(['2','4','6']), constant_term='2') p2 = Plane(normal_vector=Vector(['1','2','4']), constant_term='3') s = LinearSystem([p0,p1,p2]) print s.solve() p0 = Plane(normal_vector=Vector(['0.786','0.786','0.588']), constant_term='-0.714') p1 = Plane(normal_vector=Vector(['-0.138','-0.138','0.244']), constant_term='0.319') s = LinearSystem([p0,p1]) print s.solve() p0 = Plane(normal_vector=Vector(['8.631','5.112','-1.816']), constant_term='-5.113') p1 = Plane(normal_vector=Vector(['4.315','11.132','-5.27']), constant_term='-6.775') p2 = Plane(normal_vector=Vector(['-2.158','3.01','-1.727']), constant_term='-0.831')
from plane import Plane from vector import Vector from linsys import LinearSystem from decimal import Decimal #question 1 p1 = Plane(normal_vector=Vector([float('5.862'),float('1.178'),float('-10.366')]), constant_term=float('-8.15')) p2 = Plane(normal_vector=Vector([float('-2.931'),float('-0.589'),float('5.183')]), constant_term=float('-4.075')) s = LinearSystem([p1,p2]) r = s.solve_system() print r #question 2 p1 = Plane(normal_vector=Vector([float('8.631'),float('5.112'),float('-1.816')]), constant_term=float('-5.113')) p2 = Plane(normal_vector=Vector([float('4.315'),float('11.132'),float('-5.27')]), constant_term=float('-6.775')) p3 = Plane(normal_vector=Vector([float('-2.158'),float('3.01'),float('-1.727')]), constant_term=float('-0.831')) s = LinearSystem([p1,p2, p3]) r = s.solve_system() print r #question 3 p1 = Plane(normal_vector=Vector([float('5.262'),float('2.739'),float('-9.878')]), constant_term=float('-3.441')) p2 = Plane(normal_vector=Vector([float('5.111'),float('6.358'),float('7.638')]), constant_term=float('-2.152')) p3 = Plane(normal_vector=Vector([float('2.016'),float('-9.924'),float('-1.367')]), constant_term=float('-9.278')) p4 = Plane(normal_vector=Vector([float('2.167'),float('-13.543'),float('-18.883')]), constant_term=float('-10.567')) s = LinearSystem([p1,p2,p3,p4]) r = s.solve_system() print r
def test_intersect2(self): p = Plane() r = Ray(Point(0, 0, 0), Vector(0, 0, 1)) xs = p.local_intersect(r) self.assertEqual(0, xs.count)
temp = [ 'Equation {}: {}'.format(i + 1, p) for i, p in enumerate(self.planes) ] ret += '\n'.join(temp) return ret class MyDecimal(Decimal): def is_near_zero(self, eps=1e-10): return abs(self) < eps if __name__ == '__main__': p0 = Plane(normal_vector=Vector(['1', '1', '1']), constant_term='1') p1 = Plane(normal_vector=Vector(['0', '1', '0']), constant_term='2') p2 = Plane(normal_vector=Vector(['1', '1', '-1']), constant_term='3') p3 = Plane(normal_vector=Vector(['1', '0', '-2']), constant_term='2') s = LinearSystem([p0, p1, p2, p3]) print(s.indices_of_first_nonzero_terms_in_each_row()) print('{},{},{},{}'.format(s[0], s[1], s[2], s[3])) print(len(s)) print(s) s[0] = p1 print(s) print(MyDecimal('1e-9').is_near_zero())
class Controller(): def __init__(self, source_path=None, save_path='/home/pi/Desktop/Rhapsody-of-nonsense/records/', save=1, debug=0): """debug: manual read video (" ", "x"), and no use PIGPIO""" self.debug = debug self.frame_queue = Queue(1) self.feedback_queue = Queue() self.record = Record(self.frame_queue, debug=self.debug, feedback_queue=self.feedback_queue, source_path=source_path, save=save, save_path=save_path) self.source_path = source_path self.frame_new = None self.c = C_START self._stop = 0 self.box = Box() self.light_color = 0 self.color = 'r' self.need_drop = False self.dropped = False if not debug: try: self.plane = Plane() except: display('Error: Failed to connect plane') raise IOError elif __name__ == '__main__': self.plane = Plane(debug=1) def mission_start(self): # all mission fun return "ret, pitch, roll, yaw" # self.following_loiter(light_only=True) #owowow # self.plane.update(1, 0, 0, 0) # # self.loop(self.pause, sec=2) # # self.loop(self.forward_no_yaw_experimental, self.condition_light, sec=5) # self.loop(self.forward_experimental, sec=90) #owoowow self.plane.update(1, 0, 0, 0) # self.loop(self.forward_experimental, self.condition_light, sec=30) self.loop(self.forward_no_yaw_experimental, self.condition_light, sec=30) self.plane.update(1, 0, 0, 0) self.plane.pitch_pid.set_pid(kp=0, ki=0.35, kd=0) self.plane.roll_pid.set_windup_guard(40) self.loop(self.stable_rad, self.condition_not_red, sec=30) # self.loop(self.pause, self.condition_not_red, sec=10) if self.light_color == 2: self.color = 'g' elif self.light_color == 3: self.color = 'b' else: self.color = 'r' print('Color:', self.color) self.plane.pitch_pid.reset() self.plane.roll_pid.reset() self.plane.update(1, 90, 0, 0) self.loop(self.pause_color, self.condition_no_light, sec=10) self.loop(self.pause_color, sec=1.5) self.following(ignore_light=True, drop=True) self.following(ignore_light=True) # def const(self) def conditoin_drop(self): return self.condition_has_color() def condition_not_red(self): self.light_color = self.condition_has_light() if self.light_color > 1: return True return False def following_loiter(self, light_only=False, ignore_light=False): while True: if light_only: self.loop(self.forward_loiter, self.condition_light, sec=30) else: if ignore_light: self.loop(self.forward_loiter, self.condition_forward, sec=30) else: self.loop(self.forward_loiter, self.condition_forward_light, sec=30) # self.loop(self.forward_loiter, self.forward_condition, sec=30) # self.loop(self.forward, self.forward_condition, sec=30) if not ignore_light: if self.light_color: break self.plane.update(1, -45, 0, 0) self.loop(self.pause, sec=3) def following(self, light_only=False, ignore_light=False, drop=False): while True: if drop: self.loop(self.forward_experimental, self.condition_forward_color, sec=30) if light_only: self.loop(self.forward_experimental, self.condition_light, sec=30) else: if ignore_light: self.loop(self.forward_experimental, self.condition_forward, sec=30) else: self.loop(self.forward_experimental, self.condition_forward_light, sec=30) # self.loop(self.forward, self.forward_condition, sec=30) if drop: if self.need_drop: self.box.drop() self.dropped = True break if not ignore_light: if self.light_color: break self.plane.update(1, -45, 0, 0) self.loop(self.pause, sec=3) def condition_forward_color(self): if self.condition_find_color() and self.condition_has_color(): self.need_drop = True return True if self.condition_forward(): return True self.need_drop = False return False def loop(self, func_loop, func_condition=None, sec=10): condition_count = 0 now = time() while time() - now < sec: if self.dropped == True: self.feedback_queue.put('8===Dropped===') self.feedback_queue.put('9===Loop Time: {}==='.format( int(time() - now))) if self._stop: break self._get_frame() if func_condition: if func_condition(): condition_count += 1 else: condition_count = 0 if condition_count > 10: break func_loop() self.frame_finish() # def pause(self): # self.feedback_queue.put('1PAUSE') def pause(self): self.feedback_queue.put('1===PAUSE===') def pause_color(self): self.feedback_queue.put('1===PAUSE, Color: {}==='.format(self.color)) # def turn_condition(self): # front_x = self._find_center(mask=MASK_FORWARD, data='x') # print('front x', front_x) # if front_x > 15: # return True # return False # def turn(self): # pitch = 0 # # check break condition # # ret, _, roll, yaw = self._stabilize() # ret, pitch_fector, roll, yaw = self._along() # # if self.debug: # # print('ret: {}\t pitch overrided: {}\t pitch fector: {}\t roll: {}\t yaw: {}'.format(ret, pitch_overrided, pitch_fector, roll, yaw)) # # print(ret, pitch, roll, yaw, sep='\t') # # Testing # # self.plane.update(ret, pitch_overrided, roll, yaw) # self.plane.update(ret, pitch, 0, yaw) def pitch_test(self, pitch, sec=10): now = time() while time() - now < sec: self._get_frame() # check break condition # ret, _, roll, yaw = self._stabilize() # ret, pitch_fector, roll, yaw = self._along() # _, yy, _, thr = self._find_center(self.frame_new, MASK_BREAK) # self.feedback_queue.put(1, 160, yy) # # pitch_overrided = int(pitch * pitch_fector) # pitch_overrided = pitch + int((yy - 120) * -1.0) self.plane.update(1, pitch, 0, 0) self.frame_finish() def condition_forward_light(self): self.light_color = self.condition_has_light() if self.light_color: return True yaw_weight = self._find_center(mask=MASK_FORWARD, data='w') print('yaw weight', yaw_weight) if yaw_weight < 10: return True return False def condition_light(self): self.light_color = self.condition_has_light() if self.light_color: return True yaw_weight = self._find_center(mask=MASK_FORWARD, data='w') print('yaw weight', yaw_weight) if yaw_weight < 10: global_weight = self._find_center(mask=MASK_ALL, data='w') if global_weight < 100: return True return False def condition_no_light(self): self.light_color = self.condition_has_light() if not self.light_color: return True return False def condition_forward(self): yaw_weight = self._find_center(mask=MASK_FORWARD, data='w') print('yaw weight', yaw_weight) if yaw_weight < 10: global_weight = self._find_center(mask=MASK_ALL, data='w') if global_weight < 100: return True return False def forward_loiter(self): self.feedback_queue.put('1===Forward Loiter===') pitch = 70 self.plane.update(1, pitch, 0, 0) def forward(self): self.feedback_queue.put('1===Forward===') pitch = 70 # check break condition # ret, _, roll, yaw = self._stabilize() ret, pitch_fector, roll, yaw = self._along() pitch_ = self._find_center(mask=MASK_OWO, data='y') pitch_overrided = int(pitch * pitch_fector) # if yy > 150: # pitch_overrided += int(pitch_ * -1.0) # else: # pitch_overrided = int(pitch * pitch_fector) # if self.detect(self.frame_new) == 'R': # self.box.drop() # # pitch_overrided = 0 # else: # self.box.close() # if self.debug: print( 'ret: {}\t pitch overrided: {}\t pitch fector: {}\t roll: {}\t yaw: {}' .format(ret, pitch_overrided, pitch_fector, roll, yaw)) # print(ret, pitch, roll, yaw, sep='\t') # Testing # self.plane.update(ret, pitch_overrided, roll, yaw) self.plane.update(ret, pitch_overrided, roll, yaw) def forward_experimental(self): self.feedback_queue.put('1===Forward Experimental===') pitch = 70 # check break condition ret, pitch_fector, roll, yaw = self._along_experimental() # front_weight = self._find_center(mask=MASK_FORWARD, data='w') # if front_weight < 10: # # use global center instead # yaw = self._find_center(mask=MASK_ALL, data='x') # pitch_ = self._find_center(mask=MASK_OWO, data='y') pitch_overrided = int(pitch * pitch_fector) # if self.debug: print( 'ret: {}\t pitch overrided: {}\t pitch fector: {}\t roll: {}\t yaw: {}' .format(ret, pitch_overrided, pitch_fector, roll, yaw)) # print(ret, pitch, roll, yaw, sep='\t') # Testing # self.plane.update(ret, pitch_overrided, roll, yaw) self.plane.update(ret, pitch_overrided, roll, yaw) def forward_no_yaw_experimental(self): self.feedback_queue.put('1===Forward Experimental (w/o Yaw)===') pitch = 70 # check break condition ret, pitch_fector, roll, yaw = self._along_experimental() # pitch_ = self._find_center(mask=MASK_OWO, data='y') front_weight = self._find_center(mask=MASK_FORWARD, data='w') if front_weight < 10: # use global center instead roll = self._find_center(mask=MASK_ALL, data='x') pitch_overrided = int(pitch * pitch_fector) # if self.debug: print( 'ret: {}\t pitch overrided: {}\t pitch fector: {}\t roll: {}\t yaw: {}' .format(ret, pitch_overrided, pitch_fector, roll, yaw)) # print(ret, pitch, roll, yaw, sep='\t') # Testing # self.plane.update(ret, pitch_overrided, roll, yaw) self.plane.update(ret, pitch_overrided, roll, 0) def forward_no_yaw(self): self.feedback_queue.put('1===Forward No Yaw===') pitch = 70 # check break condition # ret, _, roll, yaw = self._stabilize() ret, pitch_fector, roll, yaw = self._along_no_yaw() pitch_ = self._find_center(mask=MASK_OWO, data='y') pitch_overrided = int(pitch * pitch_fector) # if self.debug: print( 'ret: {}\t pitch overrided: {}\t pitch fector: {}\t roll: {}\t yaw: {}' .format(ret, pitch_overrided, pitch_fector, roll, yaw)) # print(ret, pitch, roll, yaw, sep='\t') # Testing # self.plane.update(ret, pitch_overrided, roll, yaw) self.plane.update(ret, pitch_overrided, roll, 0) def forward_backup(self, pitch=100, sec=10): now = time() while time() - now < sec: if self._stop: break self._get_frame() # check break condition # ret, _, roll, yaw = self._stabilize() ret, pitch_fector, roll, yaw = self._along() pitch_ = self._find_center(mask=MASK_OWO, data='y') pitch_overrided = int(pitch * pitch_fector) # if yy > 150: # pitch_overrided += int(pitch_ * -1.0) # else: # pitch_overrided = int(pitch * pitch_fector) if self.detect(self.frame_new) == 'R': self.box.drop() # pitch_overrided = 0 else: self.box.close() # if self.debug: print( 'ret: {}\t pitch overrided: {}\t pitch fector: {}\t roll: {}\t yaw: {}' .format(ret, pitch_overrided, pitch_fector, roll, yaw)) # print(ret, pitch, roll, yaw, sep='\t') # Testing # self.plane.update(ret, pitch_overrided, roll, yaw) self.plane.update(ret, pitch_overrided, roll, yaw) self.frame_finish() def stable(self, sec=10): now = time() while time() - now < sec: if self._stop: break self._get_frame() # check break condition ret, pitch, roll, yaw = self._stabilize() if self.debug: print('ret: {}\t pitch: {}\t roll: {}\t yaw: {}'.format( ret, pitch, roll, yaw)) # print(ret, pitch, roll, yaw, sep='\t') self.plane.update(ret, pitch, roll, yaw) self.frame_finish() def _stabilize(self, color='k'): pitch = self._find_center(mask=MASK_OWO, data='y') roll = self._find_center(mask=MASK_LINE_MIDDLE, data='x') return 1, pitch, roll, 0 def _along(self, color='k'): yaw = self._find_center(mask=MASK_FORWARD, data='x') yaw_weight = self._find_center(mask=MASK_FORWARD, data='w') # roll = self._find_center(mask=MASK_LINE_MIDDLE, data='x') roll = self._find_center(mask=MASK_LINE_BACKWARD, data='x') # yaw-roll for parallelity yaw_overrided = yaw - roll if abs(yaw_overrided) > 40: pitch_fector = 0.3 # pitch_fector = 1 else: pitch_fector = 1 if yaw_weight < 10: pitch_fector = 0.3 # yaw_overrided = -90 return 1, pitch_fector, roll, yaw_overrided def _along_experimental(self, color='k'): front = self._find_center(mask=MASK_FORWARD, data='x') front_weight = self._find_center(mask=MASK_FORWARD, data='w') # roll = self._find_center(mask=MASK_LINE_MIDDLE, data='x') back = self._find_center(mask=MASK_LINE_BACKWARD, data='x') # yaw-roll for parallelity yaw_overrided = front - back roll_overrided = front if abs(yaw_overrided) > 40: pitch_fector = 0.3 # pitch_fector = 1 else: pitch_fector = 1 if front_weight < 10: # use global center instead pitch_fector = 0.3 yaw_overrided = self._find_center(mask=MASK_ALL, data='x') if yaw_overrided * back == 0: yaw_overrided = 0 # yaw_overrided = -90 return 1, pitch_fector, roll_overrided, yaw_overrided def _along_no_yaw(self, color='k'): yaw = self._find_center(mask=MASK_FORWARD, data='x') yaw_weight = self._find_center(mask=MASK_FORWARD, data='w') roll = self._find_center(mask=MASK_LINE_MIDDLE, data='x') # roll = self._find_center(mask=MASK_LINE_BACKWARD, data='x') # yaw-roll for parallelity yaw_overrided = yaw - roll if abs(yaw_overrided) > 40: pitch_fector = 0.3 # pitch_fector = 1 else: pitch_fector = 1 if yaw_weight < 10: pitch_fector = 0.3 # yaw_overrided = -90 return 1, pitch_fector, roll, yaw_overrided def detect(self, frame): """顏色轉換時EX 紅-> 綠有機會誤判藍 之類的,須加上一部份延遲做防誤判。 """ frame = cv2.GaussianBlur(frame, (13, 13), 0) r = frame[:, :, 2] g = frame[:, :, 1] b = frame[:, :, 0] a = r - g + 220 c = b - r + 220 ans = cv2.hconcat([a, c]) ans = cv2.cvtColor(ans, cv2.COLOR_GRAY2BGR) _, a = cv2.threshold(a, 100, 255, cv2.THRESH_BINARY_INV) _, c = cv2.threshold(c, 100, 255, cv2.THRESH_BINARY_INV) na = cv2.countNonZero(a) nb = cv2.countNonZero(c) if na > 5000: if nb > 2500: print("G", na, nb) return 'G' else: print("R", na, nb) return 'R' else: if nb > 2500: print("B", na, nb) return 'B' else: print("XX", na, nb) return 'X' return ans def stable_rad(self): self.feedback_queue.put('1===Stable Red===') frame = self.frame_new r = frame[:, :, 2] g = frame[:, :, 1] a = r - g + 220 _, a = cv2.threshold(a, 100, 255, cv2.THRESH_BINARY_INV) pitch = self._find_center(frame=a, mask=MASK_ALL, data='y') roll = self._find_center(frame=a, mask=MASK_ALL, data='x') self.plane.update(1, pitch, roll, 0) def condition_has_light(self): """顏色轉換時EX 紅-> 綠有機會誤判藍 之類的,須加上一部份延遲做防誤判。""" frame = self.frame_new r = frame[:, :, 2] g = frame[:, :, 1] b = frame[:, :, 0] a = r - g + 220 c = b - r + 220 _, a = cv2.threshold(a, 100, 255, cv2.THRESH_BINARY_INV) _, c = cv2.threshold(c, 100, 255, cv2.THRESH_BINARY_INV) na = cv2.countNonZero(a) nb = cv2.countNonZero(c) if na > 5000: if na > nb: print('R', na, nb) return 1 else: print('G', na, nb) return 2 else: if nb > 5000: print('B', na, nb) return 3 else: print('X', na, nb) return 0 def condition_has_color(self): hsv = cv2.cvtColor(self.frame_new, cv2.COLOR_BGR2HSV) h = hsv[:, :, 0] s = hsv[:, :, 1] v = hsv[:, :, 2] _, s_ = cv2.threshold(s, 100, 255, cv2.THRESH_BINARY) hW = self._find_center((None, None, 0, 0), data='w', frame=s_) if hW > 3000: return 1 else: return 0 def condition_find_color(self): # b100, r180, g54 hRange = 10 if self.color == 'r': offset = 255 elif self.color == 'g': offset = 54 * 255 / 180 elif self.color == 'b': offset = 100 * 255 / 180 hsv = cv2.cvtColor(self.frame_new, cv2.COLOR_BGR2HSV) h = hsv[:, :, 0] / 180 * 255 - offset + hRange h = np.asarray(h, np.uint8) _, h_ = cv2.threshold(h, 2 * hRange, 255, cv2.THRESH_BINARY_INV) hW = self._find_center(mask=(None, 50, 0, 0), data='w', frame=h_) # hW = self._find_center(mask=(50, 50, 0, 0), data='w', frame=h_) # print(hW) if hW > 3000: return 1 else: return 0 def _get_frame(self): frame = self.frame_queue.get() self.binarized_frame = self._binarization_general(frame) # self.binarized_frame = self._binarization_low_light(frame) self.feedback_queue.put(self.binarized_frame) def _binarization_general(self, frame): frame = cv2.GaussianBlur(frame, (13, 13), 0) self.frame_new = frame r = frame[:, :, 2] b = frame[:, :, 0] gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) _, gray_ = cv2.threshold(gray, 80, 255, cv2.THRESH_BINARY_INV) c = b - r + 180 c = np.asarray(c, np.uint8) _, c_ = cv2.threshold(c, 160, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) binarized_frame = np.bitwise_and(c_, gray_) self.feedback_queue.put(binarized_frame) return binarized_frame def _binarization_low_light(self, frame): frame = cv2.GaussianBlur(frame, (25, 25), 0) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) thr = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 15, self.c) thr = cv2.morphologyEx(thr, cv2.MORPH_OPEN, kernel) thr = cv2.morphologyEx(thr, cv2.MORPH_CLOSE, kernel2) try: thr = cv2.bitwise_and(thr, thr) except: p(self.debug, 'Something went wrong when do bitwise operation') p(self.debug, 'Image shape: {}'.format(thr.shape)) contours, _ = cv2.findContours(thr, 1, 2) sumX = 0 sumY = 0 sumW = 0 if len(contours) < 10: self.c -= delta_c if self.c < 0: self.c = 0 else: self.c += delta_c self.feedback_queue.put(thr) return thr def _mask(self, frame=None, mask=(None, None, 0, 0), img_size=IMAGE_SIZE): """mask -> (width, hight, offset_x, offset_y),width and hight are half value """ if type(frame) is not np.ndarray: frame = self.binarized_frame width, hight, offset_x, offset_y = mask mask = np.zeros(img_size, dtype=np.uint8) center_point_x = img_size[1] // 2 + offset_x center_point_y = img_size[0] // 2 - offset_y if not width: x1 = 0 x2 = img_size[1] else: x1 = center_point_x - width x2 = center_point_x + width if not hight: y1 = 0 y2 = img_size[0] else: y1 = center_point_y - hight y2 = center_point_y + hight mask[y1:y2, x1:x2] = 255 self.feedback_queue.put((1, (x1, y1), (x2, y2))) masked = np.bitwise_and(frame, mask) return masked def _find_center(self, mask, data, frame=None, error_num=10): "mask: (width, hight, offset_x, offset_y),\ndata: 'x', 'y', 'w'" thr = self._mask(frame=frame, mask=mask) center_point_x = IMAGE_SIZE[1] // 2 + mask[2] center_point_y = IMAGE_SIZE[0] // 2 - mask[3] sumX = 0 sumY = 0 sumW = 0 contours, _ = cv2.findContours(thr, 1, 2) if len(contours) < error_num: self.c -= delta_c if self.c < 0: self.c = 0 else: self.c += delta_c for cnt in contours: M = cv2.moments(cnt) if M['m00'] < 100: continue sumX += M['m10'] sumY += M['m01'] sumW += M['m00'] # M['M00'] weight # M['m10'] xMoment # M['m01'] yMoment # 全畫面的黑色的中心座標 if sumW == 0: display('Not found') # 因為 很多程式重複使用 故無法繼續使用舊值 cX = center_point_x cY = center_point_y else: cX = sumX / sumW cY = sumY / sumW # 因為 很多程式重複使用 故無法繼續使用舊值 # self.last_center = (cX, cY) if self.debug: ret_thr = thr if self.source_path: cv2.imshow('Replay', self.frame_new) while 1: inn = cv2.waitKey(1) if inn & 0xFF == ord('x'): self._stop = 1 break break else: ret_thr = None if data == 'x': self.feedback_queue.put((0, (center_point_x, center_point_y), (int(cX), center_point_y))) return cX - center_point_x if data == 'y': self.feedback_queue.put((0, (center_point_x, center_point_y), (center_point_x, int(cY)))) return center_point_y - cY if data == 'w': return sumW def frame_finish(self): self.feedback_queue.put( '0yaw: {:>6d}, roll: {:>6d}, pitch: {:>6d}, color: {}'.format( self.plane.yaw_pid.output, self.plane.roll_pid.output, self.plane.pitch_pid.output, self.color)) def stop(self): self.record.stop_rec()
COLORS = { "bg": (0, 0, 0) # 背景颜色 } FPS = 60 # 游戏帧率 WINWIDTH = 600 # 窗口宽度 WINHEIGHT = 900 # 窗口高度 MOVESTEP = 5 # 移动速度 pygame.init() # pygame初始化,必须有,且必须在开头 # 创建主窗体 clock = pygame.time.Clock() # 用于控制循环刷新频率的对象 win = pygame.display.set_mode((WINWIDTH, WINHEIGHT)) plane = Plane(win, 200, 600) hm = HuajiManager(win) mx, my = 0, 0 # 记录移动方向 while True: win.fill(COLORS["bg"]) # 获取所有事件 for event in pygame.event.get(): if event.type == pygame.QUIT: # 判断当前事件是否为点击右上角退出键 pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT or event.key == ord('a'): mx = -1
enemy.x + enemy.image.get_width()) and ( plane.y + 0.7 * plane.image.get_height() > enemy.y) and (plane.y + 0.3 * plane.image.get_height() < enemy.y + enemy.image.get_height()): return True return False for i in range(20): bullets.append(Bullet()) count_b = len(bullets) index_b = 0 interval_b = 0 plane = Plane() enemies = [] for i in range(10): enemies.append(Enemy()) while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit() if not gameover: screen.blit(background, (0, 0)) interval_b -= 1
class SlideShow(component.Component): """Slide show component. """ def __init__(self, name="SlideShow", slides=[], auto_insert=True): component.Component.__init__(self, name, auto_insert) if isinstance(slides, types.StringTypes): slides = Slide(slides) try: len(slides) except: slides = [slides] self.images = [] for s in slides: for f in s.files: self.images.append((f, s.transition)) # Currently displayed image index self.imageidx = 0 self.setup() em = eventManager() em.connect(STEP_FRAME, self) em.connect(LEFT_DOWN, self) em.connect(KEY_PRESS, self) self.transition = self.images[0][1] # Global time when the next transition starts # self.transition_start = 3.0 self.transition_start = 999999.0 # Slide show state self.state = 0 # setup def setup(self): """Setup the scene. """ scene = getScene() # Set up direction scene.up = (0,1,0) # Camera self.cam = TargetCamera( name = "SlideShow_Cam", pos = (0,0,5.6), fov = 30 ) # Set background... gradient = Image.new("RGB", (2,128)) draw = ImageDraw.Draw(gradient) colbottom = vec3(0.1, 0.1, 0.3) colmid = vec3(0.95,0.95,1) coltop = vec3(0.2, 0.2, 0.4) colormap = [colbottom, colbottom, colmid, coltop, coltop] for y in range(128): t = float(y)/128 c = spline(t, colormap) draw.line([0,y, 1,y], fill=(int(c.x*255), int(c.y*255), int(c.z*255))) back = Plane( lx=4, ly=3, pos=(0,0,-5), scale=2.4, material = GLMaterial( diffuse = (0,1,1), texture = GLTexture(image = gradient, mode = GL_REPLACE)) ) # Create plate materials... initial = Image.new("RGB", (4,4)) invY = mat4(1).translate(vec3(0,1,0)).scale(vec3(1,-1,1)) self.mat1 = GLMaterial( diffuse = (1,1,1,1), texture = GLTexture( image = initial, mode = GL_REPLACE, # size = (512,512), transform = invY, wrap_s = GL_CLAMP, wrap_t = GL_CLAMP ) ) self.backmaterial = self.mat1 self.setBackImage(self.images[0][0]) self.mat2 = GLMaterial( diffuse = (1,1,1,1), texture = GLTexture( image = initial, mode = GL_REPLACE, # size = (512,512), transform = invY, wrap_s = GL_CLAMP, wrap_t = GL_CLAMP ) ) self.backmaterial = self.mat2 self.setBackImage(self.images[1][0]) self.frontmaterial = self.mat1 self.backmaterial = self.mat2 # Create plates... self.frontplate = Plane(lx = 4, ly = 3, material = self.frontmaterial) self.backplate = Plane(lx = 4, ly = 3, pos = (0,0,-0.1), material = self.backmaterial ) self.helper = Sphere(radius=0.1, pos=(0,0,-1)) # onLeftDown def onLeftDown(self, e): if self.state==0: self.transition_start = getScene().timer().time def onKeyPress(self, e): # Page down or Enter? if e.keycode==281 or e.keycode==13: self.transition_start = getScene().timer().time # Page up elif e.keycode==280: pass # q (reset cam) elif e.key=="q": getScene().up = vec3(0,1,0) self.cam.pos = vec3(0,0,5.6) self.cam.target = vec3(0,0,0) self.cam.fov = 30 cmds.link(self.cam) # onStepFrame def onStepFrame(self): timer = getScene().timer() ### State 0: Waiting for the transition if self.state==0: if timer.time>=self.transition_start: self.state = 1 ### State 1: Begin of transition if self.state==1: self.transition.preTransition(self) eventManager().event("SlidePreTransition", self.images[self.imageidx][0]) self.state = 2 ### State 2: Transition if self.state==2: if self.transition.duration>0: t = (timer.time-self.transition_start)/self.transition.duration else: t = 1.0 if t>1.0: t = 1.0 self.transition.doTransition(self, t) eventManager().event("SlideDoTransition", t) if t==1.0: self.state = 3 ### State 3: Transition is over elif self.state==3: eventManager().event("SlidePostTransition") self.transition.postTransition(self) self.switchSlide() self.frontplate.transform = mat4(1) self.backplate.transform = mat4(1) self.backplate.pos = vec3(0,0,-1) # self.transition_start += 5.0 self.transition_start = 999999.0 self.state = 0 # switchSlide def switchSlide(self): """Prepare everything for the next slide. """ # Swap front and back material... dummy = self.frontmaterial self.frontmaterial = self.backmaterial self.backmaterial = dummy # Update the materials of the plates self.frontplate.setMaterial(self.frontmaterial) self.backplate.setMaterial(self.backmaterial) # Set the next image on the back material idx = (self.imageidx+2)%len(self.images) self.setBackImage(self.images[idx][0]) self.imageidx = (self.imageidx+1)%len(self.images) # Set the new transition object self.transition = self.images[self.imageidx][1] # setBackImage def setBackImage(self, name): """Set a new image on the back material.""" self.backmaterial.texture.imagename = name img = Image.open(name) if img.mode!="RGB" and img.mode!="RGBA": img = img.convert("RGB") self.backmaterial.texture.image = img w,h = img.size f = (4.0*h)/(3.0*w) if f>=1.0: S = mat4(1).scale(vec3(f,1,1)) S.translate(vec3(-0.5+0.5/f,0,0)) draw = ImageDraw.Draw(img) draw.line([(0,0), (0,h)], fill=(0,0,0)) draw.line([(1,0), (1,h)], fill=(0,0,0)) draw.line([(w-1,0), (w-1,h)], fill=(0,0,0)) draw.line([(w-2,0), (w-2,h)], fill=(0,0,0)) else: f = (3.0*w)/(4.0*h) S = mat4(1).scale(vec3(1,f,1)) S.translate(vec3(0,-0.5+0.5/f,0)) draw = ImageDraw.Draw(img) draw.line([(0,0), (w,0)], fill=(0,0,0)) draw.line([(0,1), (w,1)], fill=(0,0,0)) draw.line([(0,h-1), (w,h-1)], fill=(0,0,0)) draw.line([(0,h-2), (w,h-2)], fill=(0,0,0)) invY = mat4(1).translate(vec3(0,1,0)).scale(vec3(1,-1,1)) self.backmaterial.texture.transform = invY*S
def setup(self): """Setup the scene. """ scene = getScene() # Set up direction scene.up = (0,1,0) # Camera self.cam = TargetCamera( name = "SlideShow_Cam", pos = (0,0,5.6), fov = 30 ) # Set background... gradient = Image.new("RGB", (2,128)) draw = ImageDraw.Draw(gradient) colbottom = vec3(0.1, 0.1, 0.3) colmid = vec3(0.95,0.95,1) coltop = vec3(0.2, 0.2, 0.4) colormap = [colbottom, colbottom, colmid, coltop, coltop] for y in range(128): t = float(y)/128 c = spline(t, colormap) draw.line([0,y, 1,y], fill=(int(c.x*255), int(c.y*255), int(c.z*255))) back = Plane( lx=4, ly=3, pos=(0,0,-5), scale=2.4, material = GLMaterial( diffuse = (0,1,1), texture = GLTexture(image = gradient, mode = GL_REPLACE)) ) # Create plate materials... initial = Image.new("RGB", (4,4)) invY = mat4(1).translate(vec3(0,1,0)).scale(vec3(1,-1,1)) self.mat1 = GLMaterial( diffuse = (1,1,1,1), texture = GLTexture( image = initial, mode = GL_REPLACE, # size = (512,512), transform = invY, wrap_s = GL_CLAMP, wrap_t = GL_CLAMP ) ) self.backmaterial = self.mat1 self.setBackImage(self.images[0][0]) self.mat2 = GLMaterial( diffuse = (1,1,1,1), texture = GLTexture( image = initial, mode = GL_REPLACE, # size = (512,512), transform = invY, wrap_s = GL_CLAMP, wrap_t = GL_CLAMP ) ) self.backmaterial = self.mat2 self.setBackImage(self.images[1][0]) self.frontmaterial = self.mat1 self.backmaterial = self.mat2 # Create plates... self.frontplate = Plane(lx = 4, ly = 3, material = self.frontmaterial) self.backplate = Plane(lx = 4, ly = 3, pos = (0,0,-0.1), material = self.backmaterial ) self.helper = Sphere(radius=0.1, pos=(0,0,-1))
from vector import Vector from plane import Plane p_11 = Plane(Vector([-0.412, 3.806, 0.728]), -3.46) p_12 = Plane(Vector([1.03, -9.515, -1.82]), 8.65) p_21 = Plane(Vector([2.611, 5.528, 0.283]), 4.6) p_22 = Plane(Vector([7.715, 8.306, 5.342]), 3.76) p_31 = Plane(Vector([-7.926, 8.625, -7.212]), -7.952) p_32 = Plane(Vector([-2.642, 2.875, -2.404]), -2.443) print('Planes are equal:') print('p_11 and p_12: ' + str(p_11 == p_12)) print('p_21 and p_22: ' + str(p_21 == p_22)) print('p_31 and p_32: ' + str(p_31 == p_32)) print('\nPlanes are parallel but not equal:') print('p_11 and p_12: ' + str(p_11.is_parallel(p_12) and p_11 != p_12)) print('p_21 and p_22: ' + str(p_21.is_parallel(p_22) and p_21 != p_22)) print('p_31 and p_32: ' + str(p_31.is_parallel(p_32) and p_31 != p_32)) print('\nPlanes are parallel but not equal:') print('p_11 and p_12: ' + str(not p_11.is_parallel(p_12))) print('p_21 and p_22: ' + str(not p_21.is_parallel(p_22))) print('p_31 and p_32: ' + str(not p_31.is_parallel(p_32)))
# p3 = Plane(normal_vector=Vector([Decimal('1'), Decimal('0'), Decimal('-2')]), constant_term=Decimal('2')) # # s = LinearSystem([p0,p1,p2,p3]) # print s.indices_of_first_nonzero_terms_in_each_row() # print '{},{},{},{}'.format(s[0],s[1],s[2],s[3]) # print len(s) # print s # # s[0] = p1 # print s # # print MyDecimal('1e-9').is_near_zero() # print MyDecimal('1e-11').is_near_zero() p0 = Plane(normal_vector=Vector([Decimal('1'), Decimal('1'), Decimal('1')]), constant_term=Decimal('1')) p1 = Plane(normal_vector=Vector([Decimal('0'), Decimal('1'), Decimal('0')]), constant_term=Decimal('2')) p2 = Plane(normal_vector=Vector([Decimal('1'), Decimal('1'), Decimal('-1')]), constant_term=Decimal('3')) p3 = Plane(normal_vector=Vector([Decimal('1'), Decimal('0'), Decimal('-2')]), constant_term=Decimal('2')) s = LinearSystem([p0, p1, p2, p3])
from plane import Plane, Punctuation from plane.pattern import EMAIL p = Plane() text = "You can send me an email at [email protected]." def test_extract(): v = list(p.update(text).extract(EMAIL, True)) values = p.update(text).extract(EMAIL).values assert v == values assert values[0].value == "*****@*****.**" def test_replace(): p.update(text) assert p.replace(EMAIL).text == "You can send me an email at <Email>." p.update(text) assert p.replace(EMAIL, "").text == "You can send me an email at ." def test_segment(): assert p.update(text).replace(EMAIL, "").segment() == [ "You", "can", "send", "me", "an", "email", "at",
class Camera: def __init__(self, filmSize, focalLength, imagePath): # intrinsic parameters self.fieldOfView = { "x": 0.0, "y": 0.0 } self.fieldOfView['x'] = 2.0 * atan(filmSize['width'] / (2.0 * focalLength)) self.fieldOfView['y'] = 2.0 * atan(filmSize['height'] / (2.0 * focalLength)) self.zPlane = { "near": 0.1, "far": 1000.0 } self.image = { "width": 0.0, "height": 0.0, "data": None } self.loadImage(imagePath) self.canvas = { "width": 0.0, "height": 0.0 } self.canvas['width'] = 2.0 * tan(self.fieldOfView['x'] / 2.0) * self.zPlane['near'] self.canvas['height'] = 2.0 * tan(self.fieldOfView['y'] / 2.0) * self.zPlane['near'] # coordinate system self.coordSystem = { "x": np.array([1.0, 0.0, 0.0], np.float32), "y": np.array([0.0, 1.0, 0.0], np.float32), "z": np.array([0.0, 0.0, 1.0], np.float32) } def loadImage(self, imagePath): img = image.read(imagePath) self.image['width'] = img[0] self.image['height'] = img[1] self.image['data'] = img[2] def adjustRotation(self, yaw, pitch, roll): rotation = mat.rotation(yaw, pitch, roll) self.coordSystem['x'] = mat.vec3(np.dot(rotation, mat.vec4(self.coordSystem['x']))) self.coordSystem['y'] = mat.vec3(np.dot(rotation, mat.vec4(self.coordSystem['y']))) self.coordSystem['z'] = mat.vec3(np.dot(rotation, mat.vec4(self.coordSystem['z']))) def setPosition(self, x, y, z): self.position = np.array([x, y, z], np.float32) def ray(self, x, y): u = self.canvas['width'] * ((x / self.image['width']) - 0.5) v = self.canvas['height'] * ((y / self.image['height']) - 0.5) w = -self.zPlane['near'] a = np.array(self.coordSystem['x'] * u) b = np.array(self.coordSystem['y'] * v) c = np.array(self.coordSystem['z'] * w) d = mat.normalize((a + b) + c) return d def intersection(self, ray): v0 = np.array([0.0, 0.0, 0.0], np.float32) normal = np.array([0.0, 0.0, 0.1], np.float32) num = np.dot(normal, v0 - self.position) den = np.dot(normal, ray) t = num / den return self.position + t * ray def initialize(self): rect = Rectangle() rect.bottomLeft = self.intersection(self.ray(0, 0)) rect.topLeft = self.intersection(self.ray(0, self.image['height'])) rect.topRight = self.intersection(self.ray(self.image['width'], self.image['height'])) rect.bottomRight = self.intersection(self.ray(self.image['width'], 0.0)) self.pyramid = Pyramid(self.position, rect) self.plane = Plane(rect, self.image) def display(self, width, height, z, current=False, frustrum=False): self.plane.draw(width, height, z) if frustrum: self.pyramid.draw(width, height, z, current)
from vector import Vector from plane import Plane #quiz 1 plane1 = Plane(Vector([-1, 1, 1]), -2) plane2 = Plane(Vector([1, -4, 4]), 21) plane3 = Plane(Vector([7, -5, -11]), 0) print "Plane 1, 2 and 3 intersection at a point: " + plane1.intersection3( plane2, plane3) #quiz 2: adjust for possibility of no solution (0=1), for example, and for a redundant variable that renders the intersection a line rather than a point #question 1 plane1 = Plane(Vector([1, -2, 1]), -1) plane2 = Plane(Vector([1, 0, -2]), 2) plane3 = Plane(Vector([-1, 4, -4]), 0) print "Plane 1, 2 and 3 intersection: " + plane1.intersection3(plane2, plane3) #question 2 plane1 = Plane(Vector([0, 1, -1]), 2) plane2 = Plane(Vector([1, -1, 1]), 2) plane3 = Plane(Vector([3, -4, 1]), 1) print "Plane 4, 5 and 6 intersection: " + plane1.intersection3(plane2, plane3) #question 3 plane1 = Plane(Vector([1, 2, 1]), -1) plane2 = Plane(Vector([3, 6, 2]), 1) plane3 = Plane(Vector([-1, -2, -1]), 1) print "Plane 7, 8 and 9 intersection: " + plane1.intersection3(plane2, plane3)
from vector import Vector from plane import Plane from lin_sys import LinearSystem from decimal import Decimal p1 = Plane(Vector(['5.862', '1.178', '-10.366']), '-8.15') p2 = Plane(Vector(['-2.391', '-0.589', '5.183']), '-4.075') ls = LinearSystem([p1, p2]).compute_rref() print(ls) print('->') print(ls.solve()) p1 = Plane(Vector(['8.631', '5.112', '-1.816']), '-5.113') p2 = Plane(Vector(['4.315', '11.132', '-5.27']), '-6.775') p3 = Plane(Vector(['-2.158', '3.01', '-1.727']), '-0.831') ls = LinearSystem([p1, p2, p3]).compute_rref() print(ls) print('->') print(ls.solve()) p1 = Plane(Vector(['5.262', '2.739', '-9.878']), '-3.441') p2 = Plane(Vector(['5.111', '6.358', '7.638']), '-2.152') p3 = Plane(Vector(['2.016', '-9.92', '-1.367']), '-9.278') p4 = Plane(Vector(['2.167', '-13.543', '-18.883']), '-10.567') ls = LinearSystem([p1, p2, p3, p4]).compute_rref() print(ls) print('->') print(ls.solve())
from camera import Camera WIN_SIZE = 800 # Screen window size (square) SHINY_RED = Material(Colour(0.7, 0.1, 0.2), Colour(0.4, 0.4, 0.4), 100, .2) SHINY_BLUE = Material(Colour(0.2, 0.3, 0.7), Colour(0.8, 0.8, 0.8), 200, .3) MATT_GREEN = Material(Colour(0.1, 0.85, 0.1)) CHECK_FLOOR = Material( None, None, None, None, Texture_Check(6, Colour(0, 0, 0), Colour(0.5, 0.5, 0.5))) scene = Scene([ Sphere(Point3(0.35, 0.6, 0.5), 0.25, SHINY_BLUE), Difference([ Intersection([ # Bowl Plane(Point3(0.1, 0.175, 0.8), Vector3(0.4, 1, 0.3), SHINY_BLUE), Sphere(Point3(0.1, 0.175, 0.8), 0.175, SHINY_BLUE), ]), Sphere(Point3(0.1, 0.175, 0.8), 0.165, SHINY_BLUE) ]), Sphere(Point3(0.75, 0.17, .8), 0.17, SHINY_RED), Plane(Point3(0, 0, 0), Vector3(0, 1, 0), CHECK_FLOOR), Difference([ Intersection([ # Cube Plane(Point3(0.2, 0.0, 0.5), Vector3(0, -1, 0), MATT_GREEN), Plane(Point3(0.1, 0.08, 0.8), Vector3(0, 1, 0), MATT_GREEN), Plane(Point3(0.3, 0.1, 0.5), Vector3(-1, 0, 0), MATT_GREEN), Plane(Point3(0.5, 0.1, 0.5), Vector3(1, 0, 0), MATT_GREEN), Plane(Point3(0.5, 0.1, 1.3), Vector3(0, 0, 1), MATT_GREEN), Plane(Point3(0.5, 0.1, 1), Vector3(0, 0, -1), MATT_GREEN) ]),
scene = Scene(camera, 800, 600, 70, Color.WHITE * 0.03) lights = [ Light(Point(0, 100, 0), Color.WHITE * 0.1, Color.WHITE, Color.WHITE), Light(Point(-100, 50, -80), Color.WHITE * 0.1, Color(255, 100, 100), Color(255, 200, 200)) ] objects = [ Plane( Point(0, -8.5, 0), Vector.J, Phong( Color(56, 0, 3), Color(56, 0, 3), Color.WHITE, 50, transmittance=0.8, ior=1.3, reflect_bg=True ) ), Sphere( Point(0, 0, 15), 8, Phong( Color(100, 100, 150), Color(100, 100, 150), Color.WHITE, 50, )
def test_non_parallel_planes_are_not_parallel(self): l1 = Plane(Vector([2,3,4]), 6) l2 = Plane(Vector([3,2,1]), 6) self.assertFalse(l1.parallelTo(l2)) self.assertFalse(l2.parallelTo(l1))
def test_rref_2(): p1 = Plane(normal_vector=Vector(['1', '1', '1']), constant_term='1') p2 = Plane(normal_vector=Vector(['1', '1', '1']), constant_term='2') s = LinearSystem([p1, p2]) r = s.compute_rref() assert (r[0] == p1 and r[1] == Plane(constant_term='1'))
def test_coincident_planes_are_coincident(self): l1 = Plane(Vector([1,1,1]), 1) l2 = Plane(Vector([-3,-3,-3]), -3) self.assertTrue(l1.coincidentTo(l2)) self.assertTrue(l2.coincidentTo(l1))
def test_triangular_2(): p1 = Plane(normal_vector=Vector(['1', '1', '1']), constant_term='1') p2 = Plane(normal_vector=Vector(['1', '1', '1']), constant_term='2') s = LinearSystem([p1, p2]) t = s.compute_triangular_form() assert (t[0] == p1 and t[1] == Plane(constant_term='1'))
def test_non_coincident_planes_are_not_coincident(self): l1 = Plane(Vector([1,1,1]), 1) l2 = Plane(Vector([1,1,1]), 2) self.assertFalse(l1.coincidentTo(l2)) self.assertFalse(l2.coincidentTo(l1))
Decimal('0.707150558138740933006474968216'), Decimal('-0.0826635849022828890650647196936') ]) # print('failed GE test 3') except Exception as e: print('failed GE test 3') assert False ##################################### Quiz: Coding Parametrization ########################### # Hooray all of these pass. # See https://classroom.udacity.com/courses/ud953/lessons/4624329808/concepts/48972686550923# # TODO: turn these into unit tests. # Fixed equation from github - p1 = Plane(Vector([0.786, 0.786, 0.588]), -0.714) p2 = Plane(Vector([-0.131, -0.131, 0.244]), 0.319) s = LinearSystem([p1, p2]) param_version = s.compute_gaussian_elimination(True) print("\nparam test 1:") print(param_version) p1 = Plane(Vector([8.631, 5.112, -1.816]), -5.113) p2 = Plane(Vector([4.315, 11.132, -5.27]), -6.775) p3 = Plane(Vector([-2.158, 3.01, -1.727]), -0.831) s = LinearSystem([p1, p2, p3]) param_version = s.compute_gaussian_elimination(True) print("\nparam test 2:") print(param_version) p1 = Plane(Vector([0.935, 1.76, -9.365]), -9.955)
def test_equal_overload_uses_coincident_planes(self): l1 = Plane(Vector([1,1,1]), 1) l2 = Plane(Vector([-3,-3,-3]), -3) self.assertTrue(l1 == l2)
# Pragun Maharaj, September 2, 2013 # This guy just test the plane.py file from plane import Plane import numpy.random as random def str(a): return ' '.join([b.__str__() for b in a]) #First we just create a simple plane inputPlane = Plane(1.0,1.0,1.0,1.0) print 'Input : %s'%(inputPlane,) print 'Grid points on the plane' samplePoints = inputPlane.gridPoints(20) for i in samplePoints: print str(i) print '\nAdding some noise to the points' noisySamples = [] for p in samplePoints: a = [(0.5*random.randn())+j for j in p] noisySamples.append(a) print '\nHere are some noisy sample points.' for p in noisySamples: print str(p) outputPlane = Plane.leastSquaresFit(noisySamples) print '\n%s'%(outputPlane,)
def test_parallel_planes_are_parallel(self): l1 = Plane(Vector([2,3,4]), 6) l2 = Plane(Vector([2,3,4]), 12) self.assertTrue(l1.parallelTo(l2)) self.assertTrue(l2.parallelTo(l1))
def setUp(self): self.plane = Plane() self.airport = Airport(20,[]) self.weather = MagicMock()
from linsys import LinearSystem from plane import Plane from vector import Vector p1 = Plane(normal_vector=Vector(['1', '1', '1']), constant_term='1') p2 = Plane(normal_vector=Vector(['0', '1', '1']), constant_term='2') s = LinearSystem([p1, p2]) t = s.compute_triangular_form() if not (t[0] == p1 and t[1] == p2): print('test case 1 failed') p1 = Plane(normal_vector=Vector(['1', '1', '1']), constant_term='1') p2 = Plane(normal_vector=Vector(['1', '1', '1']), constant_term='2') s = LinearSystem([p1, p2]) t = s.compute_triangular_form() if not (t[0] == p1 and t[1] == Plane(constant_term='1')): print('test case 2 failed') p1 = Plane(normal_vector=Vector(['1', '1', '1']), constant_term='1') p2 = Plane(normal_vector=Vector(['0', '1', '0']), constant_term='2') p3 = Plane(normal_vector=Vector(['1', '1', '-1']), constant_term='3') p4 = Plane(normal_vector=Vector(['1', '0', '-2']), constant_term='2') s = LinearSystem([p1, p2, p3, p4]) t = s.compute_triangular_form() if not (t[0] == p1 and t[1] == p2 and t[2] == Plane(normal_vector=Vector(['0', '0', '-2']), constant_term='2') and t[3] == Plane()): print('test case 3 failed') p1 = Plane(normal_vector=Vector(['0', '1', '1']), constant_term='1') p2 = Plane(normal_vector=Vector(['1', '-1', '1']), constant_term='2')
# test cases for basic row operations from plane import Plane from vector import Vector from linsys import LinearSystem p0 = Plane(normal_vector=Vector([float('1'), float('1'), float('1')]), constant_term=float('1')) p1 = Plane(normal_vector=Vector([float('0'), float('1'), float('0')]), constant_term=float('2')) p2 = Plane(normal_vector=Vector([float('1'),float('1'),float('-1')]), constant_term=float('3')) p3 = Plane(normal_vector=Vector([float('1'),float('0'),float('-2')]), constant_term=float('2')) s = LinearSystem([p0,p1,p2,p3]) s.swap_rows(0,1) if not (s[0] == p1 and s[1] == p0 and s[2] == p2 and s[3] == p3): print 'test case 1 failed' s.swap_rows(1,3) if not (s[0] == p1 and s[1] == p3 and s[2] == p2 and s[3] == p0): print 'test case 2 failed' s.swap_rows(3,1) if not (s[0] == p1 and s[1] == p0 and s[2] == p2 and s[3] == p3): print 'test case 3 failed' s.multiply_coefficient_and_row(1,0) if not (s[0] == p1 and s[1] == p0 and s[2] == p2 and s[3] == p3): print 'test case 4 failed' s.multiply_coefficient_and_row(-1,2) if not (s[0] == p1 and s[1] == p0 and s[2] == Plane(normal_vector=Vector([float('-1'),float('-1'),float('1')]), constant_term=float('-3')) and
from vector import Vector from plane import Plane from linsys import LinearSystem p0 = Plane(normal_vector=Vector(['1','1','1']), constant_term='1') p1 = Plane(normal_vector=Vector(['0','1','0']), constant_term='2') p2 = Plane(normal_vector=Vector(['1','1','-1']), constant_term='3') p3 = Plane(normal_vector=Vector(['1','0','-2']), constant_term='2') s = LinearSystem([p0,p1,p2,p3]) s.swap_rows(0,1) if not (s[0] == p1 and s[1] == p0 and s[2] == p2 and s[3] == p3): print('test case 1 failed') else: print('test case 1 passed') s.swap_rows(1,3) if not (s[0] == p1 and s[1] == p3 and s[2] == p2 and s[3] == p0): print('test case 2 failed') else: print('test case 2 passed') s.swap_rows(3,1) if not (s[0] == p1 and s[1] == p0 and s[2] == p2 and s[3] == p3): print('test case 3 failed') else: print('test case 2 passed') s.multiply_coefficient_and_row(1,0) if not (s[0] == p1 and s[1] == p0 and s[2] == p2 and s[3] == p3): print('test case 4 failed')
def create_cam_distribution_in_YZ(cam=None, plane_size=(0.3, 0.3), theta_params=(0, 180, 10), r_params=(0.25, 1.0, 4), plot=False): """ cam distritubution in YZ plane :param cam: :param plane_size: :param theta_params: :param phi_params: :param r_params: :param plot: :return: """ if cam == None: # Create an initial camera on the center of the world cam = Camera() f = 800 cam.set_K(fx=f, fy=f, cx=320, cy=240) # Camera Matrix cam.img_width = 320 * 2 cam.img_height = 240 * 2 # we create a default plane with 4 points with a side lenght of w (meters) plane = Plane(origin=np.array([0, 0, 0]), normal=np.array([0, 0, 1]), size=plane_size, n=(2, 2)) # We extend the size of this plane to account for the deviation from a uniform pattern # plane.size = (plane.size[0] + deviation, plane.size[1] + deviation) d_space = np.linspace(r_params[0], r_params[1], r_params[2]) t_list = [] for d in d_space: xx, yy, zz = uniform_halfCircle_in_YZ(theta_params, d, False) # YZ plane sphere_points = np.array( [xx.ravel(), yy.ravel(), zz.ravel()], dtype=np.float32) t_list.append(sphere_points) t_space = np.hstack(t_list) acc_row = r_params[2] acc_col = theta_params[2] accuracy_mat = np.zeros([ acc_row, acc_col ]) # accuracy_mat is used to describe accuracy degree for marker area cams = [] for t in t_space.T: cam = cam.clone() cam.set_t(-t[0], -t[1], -t[2]) cam.set_R_mat(Rt_matrix_from_euler_t.R_matrix_from_euler_t(0.0, 0, 0)) cam.look_at([0, 0, 0]) radius = sqrt(t[0] * t[0] + t[1] * t[1] + t[2] * t[2]) angle = np.rad2deg(np.arccos(t[1] / radius)) cam.set_radius(radius) cam.set_angle(angle) plane.set_origin(np.array([0, 0, 0])) plane.uniform() objectPoints = plane.get_points() # print "objectPoints",objectPoints imagePoints = cam.project(objectPoints) # print "imagePoints\n",imagePoints if ((imagePoints[0, :] < cam.img_width) & (imagePoints[0, :] > 0)).all(): if ((imagePoints[1, :] < cam.img_height) & (imagePoints[1, :] > 0)).all(): cams.append(cam) if plot: planes = [] plane.uniform() planes.append(plane) # plot3D(cams, planes) #TODO comment because of from mayavi import mlab return cams, accuracy_mat # ==============================Test================================================= #cams = create_cam_distribution(cam = None, plane_size = (0.3,0.3), theta_params = (0,360,10), phi_params = (0,70,5), r_params = (0.25,1.0,4), plot=True) #create_cam_distribution_in_YZ(cam = None, plane_size = (0.3,0.3), theta_params = (0,180,3), r_params = (0.3,0.9,3), plot=False) # print "cams size: ",len(cams) # -----------------------------Test for cam look at method------------------------------ # cam = Camera() # f = 800 # cam.set_K(fx = f, fy = f, cx = 320, cy = 240) #Camera Matrix # cam.img_width = 320*2 # cam.img_height = 240*2 # cam.set_t(1,1,1,"world") # cam.set_R_mat(Rt_matrix_from_euler_t.R_matrix_from_euler_t(0,np.deg2rad(0),0)) # cam.look_at([0,0,0]) # plane_size = (0.3,0.3) # plane = Plane(origin=np.array([0, 0, 0] ), normal = np.array([0, 0, 1]), size=plane_size, n = (2,2)) # plane.set_origin(np.array([0, 0, 0])) # plane.uniform() # planes = [] # planes.append(plane) # cams = [] # cams.append(cam) # plot3D(cams,planes) # # print "cam.R",cam.R # print "cam.Rt",cam.Rt # print "cam.P",cam.P # ------------------Code End-----------Test for cam look at method------------------------------ # create_cam_distribution_rotation_around_Z(cam=None, plane_size=(0.3, 0.3), theta_params=(0, 360, 10), phi_params=(45, 45, 1), # r_params=(3.0, 3.0, 1), plot=False) # create_cam_distribution_square_in_XY(cam=None, plane_size=(0.3, 0.3), theta_params=(0, 360, 5), phi_params=(45, 45, 1), # r_params=(3.0, 3.0, 1), plot=False)
image = Image.new("RGB", (width, height)) for x in range(width): for y in range(height): ray = camera.calcRay(x, y) color = camera.traceRay(level, objectlist, light, ray, BACKGROUND_COLOR) image.putpixel((x, y), (int(color[0] * 255), int( color[1] * 255), int(color[2] * 255))) image.save("raytracer_recursive.png", "PNG") if __name__ == "__main__": """Camerasettings""" camera = Camera(45, Point(0, 2, 10), Vector(0, 1, 0), Point(0, 3, 0)) """Light""" light = Light(Point(30, 30, 10), 1) """Materialsettings - Color, AmbientFactor, DiffuseFactor, SpecularFactor, n, ReflectionFactor""" redMaterial = Material(Color(0.7, 0, 0), 0.3, 0.7, 0.2, 10, 0.11) greenMaterial = Material(Color(0, 0.7, 0), 0.3, 0.7, 0.2, 10, 0.11) blueMaterial = Material(Color(0, 0, 0.7), 0.3, 0.7, 0.2, 10, 0.11) planeMaterial = Material(Color(0.5, 0.5, 0.5), 0.2, 0.5, 0, 0, 0) sphereRed = Sphere(Point(2.5, 3, -10), 2, redMaterial) sphereGreen = Sphere(Point(-2.5, 3, -10), 2, greenMaterial) sphereBlue = Sphere(Point(0, 7, -10), 2, blueMaterial) plane = Plane(Point(0, 0, 0), Vector(0, 1, 0), planeMaterial) objlist = [plane, sphereRed, sphereGreen, sphereBlue] """Initialize Viewport""" drawView(camera, objlist, WIDTH, HEIGHT, BACKGROUND_COLOR, light, 1)