def __init__(self, type, lane): self.previous_car = None self.in_map = True self.following = None self.car_normal_image = image.create(50, 50, image.SolidColorImagePattern(color=(0, 0, 255, 255))) self.car_emergency_image = image.create(50, 50, image.SolidColorImagePattern(color=(255, 0, 0, 255))) self.lane = lane self.type = type self.from_direction = lane.get_from() self.appear_time = time.time() self.removed = False self.has_started = False self.state = "running" self.has_set_occupied = False self.has_unset_occupied = False # self.stoppable = True if self.type is "normal": super(Car, self).__init__(self.car_normal_image) elif self.type is "emergency": super(Car, self).__init__(self.car_emergency_image) if self.from_direction is "north": self.position = (350, 850) if self.from_direction is "east": self.position = (850, 450) if self.from_direction is "south": self.position = (450, -50) if self.from_direction is "west": self.position = (-50, 350) pyglet.clock.schedule_interval(self.traffic_light_control, 0.01)
def draw_road(self): road_image_1 = image.create(200, 800, image.SolidColorImagePattern(color=(190, 190, 190, 255))) road_image_2 = image.create(800, 200, image.SolidColorImagePattern(color=(190, 190, 190, 255))) road_1 = Sprite(road_image_1, position=(400, 400)) road_2 = Sprite(road_image_2, position=(400, 400)) self.add(road_1) self.add(road_2) self.draw_line()
def gen_cube_map(self): self._right = image.create(self._image_size, self._image_size, image.CheckerImagePattern()) self._back = image.create(self._image_size, self._image_size, image.CheckerImagePattern()) self._left = image.create(self._image_size, self._image_size, image.CheckerImagePattern()) # self._front = image.create(self._image_size, self._image_size, image.CheckerImagePattern()) # self._top = image.create(self._image_size, self._image_size, image.CheckerImagePattern()) # self._bottom = image.create(self._image_size, self._image_size, image.CheckerImagePattern()) # # TOP # face = 0 # start = datetime.now() # self._set_image_data(self._top, self.multi_proc_image(face)) # el = datetime.now() - start # print "Face: %d Elapsed: %d.%3.0f" % (face, el.seconds, el.microseconds / 1000.0) # BACK face = 1 start = datetime.now() self._set_image_data(self._back, self.multi_proc_image(face)) el = datetime.now() - start print "Face: %d Elapsed: %d.%3.0f" % (face, el.seconds, el.microseconds / 1000.0) # RIGHT face = 2 start = datetime.now() self._set_image_data(self._right, self.multi_proc_image(face)) el = datetime.now() - start print "Face: %d Elapsed: %d.%3.0f" % (face, el.seconds, el.microseconds / 1000.0) # # BOTTOM # face = 3 # start = datetime.now() # self._set_image_data(self._bottom, self.multi_proc_image(face)) # el = datetime.now() - start # print "Face: %d Elapsed: %d.%3.0f" % (face, el.seconds, el.microseconds / 1000.0) # # FRONT # face = 4 # start = datetime.now() # self._set_image_data(self._front, self.multi_proc_image(face)) # el = datetime.now() - start # print "Face: %d Elapsed: %d.%3.0f" % (face, el.seconds, el.microseconds / 1000.0) # LEFT face = 5 start = datetime.now() self._set_image_data(self._left, self.multi_proc_image(face)) el = datetime.now() - start print "Face: %d Elapsed: %d.%3.0f" % (face, el.seconds, el.microseconds / 1000.0)
def __init__(self,position): self.signal = "red" self.red_image = image.create(50,50,image.SolidColorImagePattern(color=(255,0,0,255))) self.green_image = image.create(50,50,image.SolidColorImagePattern(color=(50,205,50,255))) super(TrafficLight,self).__init__(self.red_image) if position is "north": self.position = (250,550) if position is "east": self.position = (550,550) if position is "south": self.position = (550, 250) if position is "west": self.position = (250,250)
def __init__(self, w, h, *elements, **kwargs): self._elements = [] self._namedElements = {} data = (ctypes.c_ubyte * w * h * 4)() pitch = w * 4 surface = cairo.ImageSurface.create_for_data (data, cairo.FORMAT_ARGB32, w, h, pitch); context = cairo.Context(surface) self.surface = surface self.context = context self.size = w, h self.pitch = pitch for e in elements: if issubclass(e.__class__, UiElement): self.add(e) e.drawContext() imgdata = Image.frombuffer('RGBA', (w, h), surface.get_data(), 'raw', 'BGRA', 0, 1).tostring('raw', 'RGBA', 0, 1) img = image.create(w, h) img.set_data('RGBA', pitch, imgdata) super(CairoUI, self).__init__(img) self.needRedraw = False self.hasPointer = False self.interactive = kwargs.get('interactive', True) self.schedule(self.drawElements)
def __init__(self, w, h, *elements, **kwargs): self._elements = [] self._namedElements = {} data = (ctypes.c_ubyte * w * h * 4)() pitch = w * 4 surface = cairo.ImageSurface.create_for_data(data, cairo.FORMAT_ARGB32, w, h, pitch) context = cairo.Context(surface) self.surface = surface self.context = context self.size = w, h self.pitch = pitch for e in elements: if issubclass(e.__class__, UiElement): self.add(e) e.drawContext() imgdata = Image.frombuffer('RGBA', (w, h), surface.get_data(), 'raw', 'BGRA', 0, 1).tostring('raw', 'RGBA', 0, 1) img = image.create(w, h) img.set_data('RGBA', pitch, imgdata) super(CairoUI, self).__init__(img) self.needRedraw = False self.hasPointer = False self.interactive = kwargs.get('interactive', True) self.schedule(self.drawElements)
def __init__(self, theApp): ''' theApp: refernecja do obiektu aplikacji. Potrzebne przy dodawaniu obiektu nasłuchującego wejścia. ''' self.__theApp = theApp # obiekt zarządzający aplikacją self.__objects = [] # lista obiektów w świecie self.__spriteManager = SpriteManager() # menadżer sprite'ów self.__collisionManager = CollisionManager(self.__spriteManager) # menadżer kolizji self.__objectFactory = self.__create_object_factory(self.__spriteManager) # fabryka obiektów self.__levelManager = LevelManager(self.__objectFactory,self.__spriteManager) # menadżer poziomów self.__backgroundManager = BackgroundManager( levelManager = self.__levelManager ) self.__backgroundManager.set_window_coords( self.__theApp.get_window_coords() ) self.__backgroundManager.set_window_draw_dim( self.__theApp.get_window_draw_dim() ) self.__levelManager.set_window_coords( self.__theApp.get_window_coords() ) self.__levelManager.set_window_draw_dim( self.__theApp.get_window_draw_dim() ) if not self.__levelManager.load_level("demo_level"): assert True, "Tworzenie świata nie powiodło się. Nie można wczytać poziomu." const.renderTextureSize = (512,256) # rozmiary tekstury, do której będziemy renderować self.__renderTexture = image.create( *const.renderTextureSize ).get_texture() # Dodaj obiekt helikoptera i jeepa do gry # # FIXME: jeep? # self.add_object( self.__create_heli() )
def __init__(self, width=400, height=300, **kwds): super(BufferedAutogeneratedTerrain, self).__init__(width, height, **kwds) self.buffer_image = image.create(self.boundingbox.width, self.boundingbox.height).create_texture(image.Texture) for i in range(0, self.boundingbox.width): y = self.heights[i] region = self.terrain_graphic.get_region(0, self.terrain_graphic.height - y, self.terrain_graphic.width, y) self.buffer_image.blit_into(region, int(i), 0, 0)
def _make_mini_graphic(self, width): heights = self._generate_mini_heights(width) graphic = image.create(width, 10).create_texture(image.Texture) y_scale = 20.0 / self.boundingbox.height bar = self._mini_terrain_graphic for x in xrange(len(heights)): y = int(math.ceil(heights[x] * y_scale)) region = bar.get_region(0, bar.height - y, bar.width, y) graphic.blit_into(region, x, 0, 0) return graphic.image_data
def __init__(self, name=None, width=128, height=128, format="RGBA", data=None): Texture.__init__(self, "", name) self._size_x = width self._size_y = height self._format = format self._pyglet_image = image.create(self._size_x, self._size_y, image.CheckerImagePattern()) self._opengl_id = self._pyglet_image.get_texture().id if data is not None: self.set_data(self._format, len(self._format) * self._size_x, data) self._loaded = True
def __init__(self, request, test_data): super(ImageTestFixture, self).__init__(request) self.test_data = test_data self.show_checkerboard = True self.show_triangle_left = False self.show_text = True self.left_texture = None self.right_texture = None self.checkerboard = image.create(32, 32, image.CheckerImagePattern())
def test_main(self): width, height = 200, 200 self.window = w = Window(width, height, visible=False) w.push_handlers(self) self.texture = image.create(32, 32, image.CheckerImagePattern()).texture w.set_visible() while not (w.has_exit or self.has_exit): w.dispatch_events() w.close()
def _make_mini_graphic(self, width=None): if width is None: total_width = puit.gamemaster.scrollarea.width else: total_width = width graphic = image.create(total_width, 10).create_texture(image.Texture) x_scale = total_width / float(self.boundingbox.width) y_scale = 20.0 / self.boundingbox.height for part in self.get_parts(): part_width = part.boundingbox.width part_mini_width = int(round(part_width * x_scale)) part_graphic = part.get_mini_graphic(part_mini_width) part_pos_x = int(round(part.boundingbox.left * x_scale)) part_pos_y = int(round(part.boundingbox.bottom * y_scale)) graphic.blit_into(part_graphic, part_pos_x, part_pos_y, 0) return graphic
def test_save(self): self.window = w = self.create_window() w.push_handlers(self) self.screen = image.get_buffer_manager().get_color_buffer() self.checkerboard = image.create(32, 32, image.CheckerImagePattern()) self.load_texture() if self.alpha: glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) w.set_visible() while not (w.has_exit or self.has_exit): w.dispatch_events() w.close()
def test_load(self): width, height = 800, 600 self.window = w = Window(width, height, visible=False) w.push_handlers(self) self.screen = image.get_buffer_manager().get_color_buffer() self.checkerboard = image.create(32, 32, image.CheckerImagePattern()) self.load_image() if self.image: self.texture = self.image.texture if self.alpha: glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) w.set_visible() while not (w.has_exit or self.has_exit): w.dispatch_events() w.close()
def __init__(self, tex_name, tile_width, tile_height, game_state, xpos=0, ypos=0, group=None, health=3, move_pattern=unlucky, move_params=(), name='enemy', gold=1, exp=1, hitsound='bandit_hit', damage=1): super().__init__(tex_name, tile_width, tile_height, game_state, xpos=xpos, ypos=ypos, group=group, damage=damage, health=health, name=name, hitsound=hitsound) self.is_guard = 'guard' in tex_name if type(move_pattern) == str: self.move_pattern = patterns[move_pattern](self, *move_params) else: self.move_pattern = move_pattern(self, *move_params) self.game.enemies.add(self) self.stats[G] = gold self.stats[EXP] = exp self.healthbar = Sprite(create(24, 4, SolidColorImagePattern(RED)), x=self.x, y=self.y, batch=self.batch, group=self.game.groups[1])
def generate_image(self): #print int(image.get_image_data().get_data("RGBA",1024)[0]) #print image.get_image_data().get_data("RGBA",1024) self._size = 512 format_size = 4 # data = [] # for x in xrange(size * format_size): # for y in xrange(size * format_size): # if (x * y) + 1 % format_size == 0: # data.append(255) # else: # data.append(int(random() * 255)) # d = struct.pack('B'*len(data), *data) # #tex_data = (GLubyte * 1)( *d ) # imd = image.ImageData(size, size, 'RGBA', d) # im.blit_from(imd, 0, 0) start = datetime.now() self._back = image.create(self._image_size, self._image_size, image.CheckerImagePattern()) # data = numpy.random.random_integers(low=0, # high=1, # size = (size * size, format_size)) perlin_data = self.single_threaded_image() #perlin_data = self.multi_threaded_image() #perlin_data = self.multi_proc_image(0) el = datetime.now() - start print "Elapsed: %d.%3.0f" % ( el.seconds, el.microseconds / 1000.0) self._set_image_data(self._back, perlin_data)
def drawElements(self, dt): surface = self.surface context = self.context context.set_source_rgba(0, 0, 0, 0) context.set_operator(cairo.OPERATOR_SOURCE) context.paint() w, h = self.size pitch = self.pitch for i in self._elements: i.drawContext() imgdata = Image.frombuffer('RGBA', (w , h), surface.get_data(), 'raw', 'BGRA', 0, 1).tostring('raw', 'RGBA', 0, 1) img = image.create(w, h) img.set_data('RGBA', pitch, imgdata) self.image = img
def drawElements(self, dt): surface = self.surface context = self.context context.set_source_rgba(0, 0, 0, 0) context.set_operator(cairo.OPERATOR_SOURCE) context.paint() w, h = self.size pitch = self.pitch for i in self._elements: i.drawContext() imgdata = Image.frombuffer('RGBA', (w, h), surface.get_data(), 'raw', 'BGRA', 0, 1).tostring('raw', 'RGBA', 0, 1) img = image.create(w, h) img.set_data('RGBA', pitch, imgdata) self.image = img
def __init__(self, height=84, width=84, resize_ratio=1): from pyglet.gl import glEnable, glBlendFunc from pyglet.gl import GL_BLEND, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA from pyglet import window, image from pygarrayimage.arrayimage import ArrayInterfaceImage self.width = width self.height = height self.resize_ratio = resize_ratio self.window = window.Window(width=int(width * resize_ratio), height=int(height * resize_ratio), visible=False, resizable=True) self.arr = np.zeros( (int(height * resize_ratio), int(width * resize_ratio)), dtype=np.uint8) self.aii = ArrayInterfaceImage(self.arr) self.img = self.aii.texture checks = image.create(32, 32, image.CheckerImagePattern()) self.background = image.TileableTexture.create_for_image(checks) self.window.set_visible() glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
def play(frames, delay=0, magnify=1, background=None, blit_position=None, show_frame_number=True): w = window.Window(visible=False, resizable=True) arr = numpy.zeros([100, 100], dtype=numpy.uint8) aii = ArrayInterfaceImage(arr) img = aii.texture if background is None: checks = image.create(32, 32, image.CheckerImagePattern()) background = image.TileableTexture.create_for_image(checks) background_tiled = True else: if background.dtype != np.uint8: 'converting background to uint8' background = np.array(background, dtype=np.uint8) * 255 background_aii = ArrayInterfaceImage(background) background = background_aii.texture background_tiled = False if background_tiled: w.width = img.width w.height = img.height w.set_visible() else: w.width = background.width w.height = background.height w.set_visible() LIBGL_ALWAYS_SOFTWARE = 1 glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) for i, f in enumerate(frames): arr = f if arr is not None: if arr.dtype != np.uint8: 'converting' arr = np.array(arr, dtype=np.uint8) * 255 if magnify != 1: newshape = [arr.shape[0] * magnify, arr.shape[1] * magnify] arr = nim.rebin(arr, newshape) try: aii.view_new_array(arr) except: # size changed print 'size changed!' #w.width = arr.shape[1] #w.height = arr.shape[0] aii = ArrayInterfaceImage(arr) img = aii.texture w.dispatch_events() w.clear() if background_tiled: background.blit_tiled(0, 0, 0, 100, 100) #w.width, w.height) else: background.blit(0, 0, 0) # add some overlays: if show_frame_number: s = 'frame: ' + str(i) label = pyglet.text.Label(s, font_name='courier', font_size=36, x=10, y=10) label.draw() if blit_position is None: img.blit(0, 0, 0) else: img.blit(blit_position[i][1], blit_position[i][0], 0) #frame_number_text.draw() if 0: r = arr.shape[0] / 2. body_axis = npmovie.kalmanobj.long_axis[f] wing_axis = npmovie.kalmanobj.wingaxisR[f] wing_center = npmovie.kalmanobj.wingcenterR[f] #print wing_center, wing_axis if mode == 'wingimgR': print f, uframe.wingimgR.sum() pyglet.graphics.draw( 2, pyglet.gl.GL_LINES, ('v2i', (int(r), int(r), int(body_axis[1] * 10 * magnify) + int(r), int(body_axis[0] * 10 * magnify) + int(r)))) try: pyglet.graphics.draw( 2, pyglet.gl.GL_LINES, ('v2i', (int(r), int(r), int(wing_center[1] * magnify), int(wing_center[0] * magnify)))) pyglet.graphics.draw(1, pyglet.gl.GL_POINTS, ('v2i', (int(wing_center[1] * magnify), int(wing_center[0] * magnify)))) pass except: pass w.flip() time.sleep(delay) # slow down the playback w.close()
def draw_square(x, y, size, colour = (255, 255, 255, 0)): # Creates the image. img = image.create(size, size, image.SolidColorImagePattern(colour)) # Draws the image on the canvas. x, y is the top-corner of the image. img.blit(x, y)
def play(frames, delay=0, magnify=1, background=None, blit_position=None, show_frame_number=True): w = window.Window(visible=False, resizable=True) arr = numpy.zeros([100,100], dtype=numpy.uint8) aii = ArrayInterfaceImage(arr) img = aii.texture if background is None: checks = image.create(32, 32, image.CheckerImagePattern()) background = image.TileableTexture.create_for_image(checks) background_tiled = True else: if background.dtype != np.uint8: 'converting background to uint8' background = np.array(background, dtype=np.uint8)*255 background_aii = ArrayInterfaceImage(background) background = background_aii.texture background_tiled = False if background_tiled: w.width = img.width w.height = img.height w.set_visible() else: w.width = background.width w.height = background.height w.set_visible() LIBGL_ALWAYS_SOFTWARE = 1 glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) for i, f in enumerate(frames): arr = f if arr is not None: if arr.dtype != np.uint8: 'converting' arr = np.array(arr, dtype=np.uint8)*255 if magnify != 1: newshape = [arr.shape[0]*magnify, arr.shape[1]*magnify] arr = nim.rebin(arr, newshape) try: aii.view_new_array(arr) except: # size changed print 'size changed!' #w.width = arr.shape[1] #w.height = arr.shape[0] aii = ArrayInterfaceImage(arr) img = aii.texture w.dispatch_events() w.clear() if background_tiled: background.blit_tiled(0, 0, 0, 100, 100) #w.width, w.height) else: background.blit(0,0,0) # add some overlays: if show_frame_number: s = 'frame: ' + str(i) label = pyglet.text.Label(s, font_name='courier', font_size=36, x=10, y=10) label.draw() if blit_position is None: img.blit(0, 0, 0) else: img.blit(blit_position[i][1], blit_position[i][0], 0) #frame_number_text.draw() if 0: r = arr.shape[0]/2. body_axis = npmovie.kalmanobj.long_axis[f] wing_axis = npmovie.kalmanobj.wingaxisR[f] wing_center = npmovie.kalmanobj.wingcenterR[f] #print wing_center, wing_axis if mode == 'wingimgR': print f, uframe.wingimgR.sum() pyglet.graphics.draw(2, pyglet.gl.GL_LINES,('v2i', (int(r), int(r), int(body_axis[1]*10*magnify)+int(r), int(body_axis[0]*10*magnify)+int(r)))) try: pyglet.graphics.draw(2, pyglet.gl.GL_LINES,('v2i', (int(r), int(r), int(wing_center[1]*magnify), int(wing_center[0]*magnify)))) pyglet.graphics.draw(1, pyglet.gl.GL_POINTS,('v2i', (int(wing_center[1]*magnify), int(wing_center[0]*magnify)))) pass except: pass w.flip() time.sleep(delay) # slow down the playback w.close()
dialog windows slider button text input drop list check box """ main_menu = ['play', 'help', 'opions', 'exit'] import pyglet from pyglet.gl import * from pyglet.image import create, SolidColorImagePattern image = create(128, 32, SolidColorImagePattern((0x00, 0x00, 0x00, 0x7F))) texture = image.get_texture() theme = {'text_color': (0x00, 0xFF, 0xFF, 0xFF), 'border_width': 2, 'border_color': (0.0, 1.0, 1.0, 0.2), 'background_color': (0.0, 0.0, 0.0, 0.6)} g_tasks = [] visible_objects = [] def on_mouse_press(x, y, button, modifiers): for o in visible_objects: if o.hitTest((x, y)): return o.press(button, modifiers)
# test 2D array arr.shape = height, width else: # test constructor from PIL image import Image if Image.VERSION < "1.1.6": # new PIL necessary for __array_interface__ raise ValueError("Need Image (PIL) version 1.1.6 ") arr = Image.open(filename) # arr = numpy.asarray( pil_image ) aii = ArrayInterfaceImage(arr) img = aii.texture checks = image.create(32, 32, image.CheckerImagePattern()) background = image.TileableTexture.create_for_image(checks) w.width = img.width w.height = img.height w.set_visible() glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) i = 0 while not w.has_exit: w.dispatch_events() background.blit_tiled(0, 0, 0, w.width, w.height) img.blit(0, 0, 0)
def _make_mini_graphic(self, width): return image.create(width, 1, image.SolidColorImagePattern(self._colour))
+#........................#+ +#........................#+ +##########.....###########+ +++++++++++SSSSS++++++++++++ '''.strip() field_rows = [line.strip() for line in field_cells.splitlines()] cw = ch = 16 hw = hh = 8 map_height = len(field_rows) map_width = len(field_rows[0]) win = window.Window(map_width*cw, map_height*ch) # load / create image resources blank_image = image.create(cw, ch, image.SolidColorImagePattern((200,)*4)) wall_image = image.create(cw, ch, image.SolidColorImagePattern((100,)*4)) highlight_image = image.create(cw, ch, image.SolidColorImagePattern((255, 255, 255, 100))) enemy_image = image.create(hw, hh, image.SolidColorImagePattern((255, 50, 50, 255))) enemy_image.anchor_x = hw//2 enemy_image.anchor_y = hh//2 turret_image = resource.image('basic-gun.png') turret_image.anchor_x = 8 turret_image.anchor_y = 8 bullet_image = image.create(3, 3, image.SolidColorImagePattern((0,0,0,255))) bullet_image.anchor_x = 1 bullet_image.anchor_y = 1 def distance(x1, y1, x2, y2):
[18, 19, 20], [21, 22, 23], [26, 25, 24], [29, 28, 27], [30, 31, 32], [33, 34, 35] ] device.set_camera(eye=vector([0, 0, -3, 1]), at=vector([0.23, 0, 0, 1]), up=vector([0, 1, 0, 1])) # the rotate degree rotate_degree = 1 frame = image.create(device.width, device.height) fps_display = pyglet.clock.ClockDisplay() # produce texture, chess board texture = np.ones((256, 256, 4), dtype='uint8') * 255 grid_size = 32 for i in range(grid_size): for j in [j * 2 for j in range(grid_size / 2)]: texture[i * grid_size:i * grid_size + grid_size, (j + (i % 2)) * grid_size:(j + (i % 2)) * grid_size + grid_size, :] = vector([1, 128, 255, 255]) device.set_texture(texture) device.add_dir_light(vector([0, 0, 3]), vector([0.05, 0.05, 0.05]), vector([0.7, 0.7, 0.7]))
tex_coor=vector([0.0, 1.]), rhw=1) ] indices = [[0, 1, 2], [3, 4, 5], [8, 7, 6], [11, 10, 9], [14, 13, 12], [17, 16, 15], [18, 19, 20], [21, 22, 23], [26, 25, 24], [29, 28, 27], [30, 31, 32], [33, 34, 35]] device.set_camera(eye=vector([0, 0, -3, 1]), at=vector([0.23, 0, 0, 1]), up=vector([0, 1, 0, 1])) # the rotate degree rotate_degree = 1 frame = image.create(device.width, device.height) fps_display = pyglet.clock.ClockDisplay() # produce texture, chess board texture = np.ones((256, 256, 4), dtype='uint8') * 255 grid_size = 32 for i in range(grid_size): for j in [j * 2 for j in range(grid_size / 2)]: texture[i * grid_size:i * grid_size + grid_size, (j + (i % 2)) * grid_size:(j + (i % 2)) * grid_size + grid_size, :] = vector([1, 128, 255, 255]) device.set_texture(texture) device.add_dir_light(vector([0, 0, 3]), vector([0.05, 0.05, 0.05]), vector([0.7, 0.7, 0.7]))
if depth==1 and 1: # test 2D array arr.shape = height,width else: # test constructor from PIL image import Image if Image.VERSION < '1.1.6': # new PIL necessary for __array_interface__ raise ValueError("Need Image (PIL) version 1.1.6 ") arr = Image.open(filename) #arr = numpy.asarray( pil_image ) aii = ArrayInterfaceImage(arr) img = aii.texture checks = image.create(32, 32, image.CheckerImagePattern()) background = image.TileableTexture.create_for_image(checks) w.width = img.width w.height = img.height w.set_visible() glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) i=0 while not w.has_exit: w.dispatch_events() background.blit_tiled(0, 0, 0, w.width, w.height) img.blit(0, 0, 0)
# data = [] # for x in xrange(size * format_size): # for y in xrange(size * format_size): # if (x * y) + 1 % format_size == 0: # data.append(255) # else: # data.append(int(random() * 255)) # d = struct.pack('B'*len(data), *data) # #tex_data = (GLubyte * 1)( *d ) # imd = image.ImageData(size, size, 'RGBA', d) # im.blit_from(imd, 0, 0) im = image.create(size, size, image.CheckerImagePattern()) data = numpy.random.random_integers(low=0, high=1, size = (size * size, format_size)) data *= 255 #data[:,1:-1] = 0 data[:,3] = 255 data.shape = -1 tex_data = (GLubyte * data.size)(*data.astype('u1')) pitch = size * format_size # dim = image.ImageData(size,size, "RGBA", tex_data, pitch ) im.set_data("RGBA", pitch, tex_data)
def main(): oGameWindow = pyglet.window.Window(I_WIDTH, I_HEIGHT) # 顶点 # 索引 lIndice = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14], [15, 16, 17], [18, 19, 20], [21, 22, 23], [24, 25, 26], [27, 28, 29], [30, 31, 32], [33, 34, 35], ] # lVertex = [ # CVertex(vector([0, 2, 0, 1]), vector([1, 0, 0, 0]), vector([0, 0])), # CVertex(vector([0, 0, 2, 1]), vector([1, 0, 0, 0]), vector([1, 0])), # CVertex(vector([0, -2, 0, 1]), vector([1, 0, 0, 0]), vector([0, 1])), # ] # # lIndice = [ # [0, 1, 2], # ] # 纹理(棋盘格) mTexture = np.ones((256, 256, 4), dtype="uint8") grid_size = 32 for i in range(8): # 每隔1个格子 for j in [x * 2 for x in range(4)]: mTexture[i * grid_size: (i + 1) * grid_size, (j + i % 2) * grid_size: (j + i % 2 + 1) * grid_size, :] = vector([1. / 255, 128. / 255, 1, 1]) oDevice = device.CDevice(I_WIDTH, I_HEIGHT, mTexture) oCameraMgr = camera.CMgr() oCamera = oCameraMgr.GetCamera(camera.TYPE_NORMAL) oCamera.SetEye(vector([-4, 0, 0, 1])) oCamera.SetLookAt(vector([-2, 0, 0, 1])) oCamera.SetUp(vector([0, 1, 0, 0])) oCamera.SetAspect(1.0) oCamera.SetFar(300.0) oLight = light.CPointLight(1) oLightMgr = light.CMgr() oLightMgr.AddLight(oLight) oFrame = image.create(I_WIDTH, I_HEIGHT) @oGameWindow.event def on_draw(): """ 每帧调用 """ oGameWindow.clear() oDevice.ClearFrameBuffer(vector([128., 33., 78., 1])) oDevice.ClearZBuffer() global g_fDegree mModelTrans = rtmath.getRotateMatrix(vector([1, 1, 1, 0]), g_fDegree / np.pi * 180) oDevice.SetModelTrans(mModelTrans) g_fDegree += 0.0005 g_fDegree %= 180 oDevice.DrawMesh(lVertex, lIndice) mFrameBuffer = oDevice.GetFramebuffer() oFrame.set_data("RGBA", I_WIDTH * 4, mFrameBuffer.tostring()) oFrame.blit(0, 0) pyglet.clock.schedule_interval(lambda dt: None, 1 / 60.0) pyglet.app.run()
+#........................#+ +#........................#+ +##########.....###########+ +++++++++++SSSSS++++++++++++ '''.strip() field_rows = [line.strip() for line in field_cells.splitlines()] cw = ch = 16 hw = hh = 8 map_height = len(field_rows) map_width = len(field_rows[0]) win = window.Window(map_width * cw, map_height * ch) # load / create image resources blank_image = image.create(cw, ch, image.SolidColorImagePattern((200, ) * 4)) wall_image = image.create(cw, ch, image.SolidColorImagePattern((100, ) * 4)) highlight_image = image.create( cw, ch, image.SolidColorImagePattern((255, 255, 255, 100))) enemy_image = image.create(hw, hh, image.SolidColorImagePattern((255, 50, 50, 255))) enemy_image.anchor_x = hw // 2 enemy_image.anchor_y = hh // 2 turret_image = resource.image('basic-gun.png') turret_image.anchor_x = 8 turret_image.anchor_y = 8 bullet_image = image.create(3, 3, image.SolidColorImagePattern((0, 0, 0, 255))) bullet_image.anchor_x = 1 bullet_image.anchor_y = 1
def play_npmovie(npmovie, delay=0, magnify=1, mode="uimg", frames=None, framerange=None, print_frames=False): w = window.Window(visible=False, resizable=True) arr = numpy.zeros([60, 60], dtype=numpy.uint8) aii = ArrayInterfaceImage(arr) img = aii.texture w.width = img.width w.height = img.height w.set_visible() checks = image.create(32, 32, image.CheckerImagePattern()) background = image.TileableTexture.create_for_image(checks) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) if frames is None: if framerange is not None: start = framerange[0] stop = framerange[1] if stop == -1: stop = len(npmovie.uframes) frames = np.arange(start, stop) else: frames = np.arange(1, len(npmovie.uframes)) for f in frames: uframe = npmovie.uframes[f] if uframe.uimg is not None: try: if mode == "uimg": arr = uframe.uimg if mode == "legs": arr = uframe.legs if mode == "body": arr = uframe.body if mode == "wings": arr = uframe.wings if mode == "absdiff": arr = uframe.absdiff if mode == "wingimg2": arr = uframe.wingimg2 if mode == "wingimgR": arr = uframe.wingimgR if mode == "wingimgL": arr = uframe.wingimgL if mode == "wingimg": arr = uframe.wingimg if mode == "flysegs": arr = uframe.flysegs if mode == "diffthresh": arr = uframe.diffthresh if mode == "full": arr = npmovie.background arr[uframe.indices[0] : uframe.indices[1], uframe.indices[2] : uframe.indices[3]] = uframe.uimg except: arr = None if arr is not None: if arr.dtype != np.uint8: "converting" arr = np.array(arr, dtype=np.uint8) * 255 if magnify != 1: newshape = [arr.shape[0] * magnify, arr.shape[1] * magnify] arr = nim.rebin(arr, newshape) try: aii.view_new_array(arr) except: # size changed w.width = arr.shape[1] w.height = arr.shape[0] aii = ArrayInterfaceImage(arr) img = aii.texture w.dispatch_events() background.blit_tiled(0, 0, 0, w.width, w.height) img.blit(0, 0, 0) # add some overlays: r = arr.shape[0] / 2.0 body_axis = npmovie.kalmanobj.long_axis[f] if 0: wing_axis = npmovie.kalmanobj.wingaxisR[f] wing_center = npmovie.kalmanobj.wingcenterR[f] # print wing_center, wing_axis if mode == "wingimgR": print f, uframe.wingimgR.sum() pyglet.graphics.draw( 2, pyglet.gl.GL_LINES, ( "v2i", ( int(r), int(r), int(body_axis[1] * 10 * magnify) + int(r), int(body_axis[0] * 10 * magnify) + int(r), ), ), ) try: pyglet.graphics.draw( 2, pyglet.gl.GL_LINES, ("v2i", (int(r), int(r), int(wing_center[1] * magnify), int(wing_center[0] * magnify))), ) pyglet.graphics.draw( 1, pyglet.gl.GL_POINTS, ("v2i", (int(wing_center[1] * magnify), int(wing_center[0] * magnify))), ) pass except: pass w.flip() time.sleep(delay) # slow down the playback w.close()