def setupPyglet(): window = pyglet.window.Window(width=width, height=height) pygl.glClearColor(0.05, 0.04, 0.04, 1) pygl.glPointSize(10) pygl.glLineWidth(5) pygl.glEnable(pygl.GL_BLEND) pygl.glBlendFunc(pygl.GL_SRC_ALPHA, pygl.GL_ONE_MINUS_SRC_ALPHA) def on_draw(dt): window.clear() global elapsedTime outputScene.drawScene(elapsedTime) if isRecording: write_to_video() elapsedTime += dt def write_to_video(): buffer = (pygl.GLubyte * (3 * window.width * window.height))(0) pygl.glReadPixels(0, 0, width, height, pygl.GL_RGB, pygl.GL_UNSIGNED_BYTE, buffer) pipe.stdin.write(buffer) pyglet.clock.schedule_interval(on_draw, 1 / 24)
def init(self): gl.glEnableClientState(gl.GL_VERTEX_ARRAY) gl.glEnableClientState(gl.GL_COLOR_ARRAY) gl.glEnable(gl.GL_DEPTH_TEST) gl.glEnable(gl.GL_POLYGON_SMOOTH) gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glHint(gl.GL_POLYGON_SMOOTH_HINT, gl.GL_NICEST) gl.glCullFace(gl.GL_BACK) gl.glEnable(gl.GL_CULL_FACE) gl.glClearColor(*self.world.sky_color) vs_file = join(path.SOURCE, 'view', 'shaders', 'lighting.vert') vs = VertexShader(vs_file) fs_file = join(path.SOURCE, 'view', 'shaders', 'lighting.frag') fs = FragmentShader(fs_file) shader = ShaderProgram(vs, fs) shader.compile() shader.use() # create glyphs for every item added to the world before now for item in self.world: self.world_add_item(item) # create glyphs for every item added after this self.world.item_added += self.world_add_item
def on_key_release(symbol, modifiers): global firston player.pause() firston = False if not firston: print("Off colour") gl.glClearColor(*off_colour) window.clear()
def on_draw(self): gl.glClearColor(*background_color) ConfirmationWindow.clear(self) [l.draw() for l in self.labels] self.mouse_over_button.draw() self.idle_button.draw() self.vertex_list.draw(pyglet.gl.GL_LINES) self.confirm_label.draw()
def on_draw(self): gl.glClearColor(*background_color) AuthenticationWindow.clear(self) self.spr.draw() self.user_input.draw() self.vertex_list.draw(pyglet.gl.GL_LINES) self.batch.draw() self.labels.draw()
def on_draw(): # clears the background with the background color gl.glClearColor(*background) gl.glClear(gl.GL_COLOR_BUFFER_BIT) # draw in a loop boundary = winsize - 100 gap = (winsize - boundary) / 2 i_width = boundary / len(rgb1) i_height = boundary / 2 # the first line for idx, rgb in enumerate(rgb1): gl.glColor3f(*rgb) gl.glBegin( gl.GL_QUADS ) # start drawing a rectangle in counter-clockwise (CCW) order gl.glVertex2f(gap + idx * i_width, gap + i_height) # bottom left point gl.glVertex2f(gap + (idx + 1) * i_width, gap + i_height) # bottom right point gl.glVertex2f(gap + (idx + 1) * i_width, gap + boundary) # top right point gl.glVertex2f(gap + idx * i_width, gap + boundary) # top left point gl.glEnd() label = pyglet.text.Label(str(color1[idx]), font_size=7, x=gap + idx * i_width, y=gap + boundary + 20) label.draw() # # # the second line for idx, rgb in enumerate(rgb2): gl.glColor3f(*rgb) gl.glBegin( gl.GL_QUADS ) # start drawing a rectangle in counter-clockwise (CCW) order gl.glVertex2f(gap + idx * i_width, gap) # bottom left point gl.glVertex2f(gap + (idx + 1) * i_width, gap) # bottom right point gl.glVertex2f(gap + (idx + 1) * i_width, gap + i_height) # top right point gl.glVertex2f(gap + idx * i_width, gap + i_height) # top left point gl.glEnd() label = pyglet.text.Label(str(color2[idx]), font_size=7, x=gap + idx * i_width, y=gap - 20) label.draw()
def on_key_press(symbol, modifiers): global firston if symbol == key.R: print('Repeat play') boat.play() else: if not firston: firston = True player.play() if firston: print("On colour") gl.glClearColor(*on_colour) window.clear()
def __init__(self, coords, models, background_color=GREY): # original copies of each type of model self.models = models self.cube = Cube([0, 0, 0], 255) # make the objects for the cube box_model = deepcopy(self.models[BOX]) box_model.x, box_model.y, box_model.z = list(self.cube.centre) box_model.color = WHITE # doesn't matter cos not filled in box_model.scale = self.cube.edge_length / 2 self.box_model = box_model self.colour_models = [] for colour in COLOURS.values(): colour_model = deepcopy(self.models[SPHERE]) colour_model.x, colour_model.y, colour_model.z = colour colour_model.color = new_rgba(colour) colour_model.scale = 5 self.colour_models.append(colour_model) random_colours = [ # rand_colour(), # rand_colour(), # rand_colour() ] print(*random_colours, sep='\n') self.rand_col_models = [] for rc in random_colours: rc_model = deepcopy(self.models[PYRAMID]) rc_model.x, rc_model.y, rc_model.z = rc rc_model.color = new_rgba(rc) rc_model.scale = 5 self.rand_col_models.append(rc_model) # sets the background color gl.glClearColor(*background_color) # where the camera starts off: [self.x, self.y, self.z] = coords # rotation values self.rx = self.ry = self.rz = 0 self.cx, self.cy, self.cz = 0, 0, 0
def __init__(self, coords, models=None, background_color=sky): # sets the background color gl.glClearColor(*background_color) [self.x, self.y, self.z] = coords self.rx = self.ry = self.rz = 0 self.cx, self.cy, self.cz = 0, 0, 0 if models is None: self.models = [] else: if type(models) is list: self.models = models else: self.models = list(models) self.tex = pyglet.image.load('grass_top.png').get_texture()
def draw(self, viewport): gl.glClearColor(183 / 255.0, 196 / 255.0, 200 / 255.0, 1) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) x1 = viewport.tl.x x2 = viewport.br.x backgrounds = [ (self.clouds, self.clouds.width), (self.fg, self.fg.width), ] for img, w in backgrounds: cx = x1 - x1 % w - w while cx < x2: img.blit(cx, 0) cx += w
def _init_gl_parameters(self): gl.glShadeModel(gl.GL_SMOOTH) # Enable Smooth Shading gl.glClearColor(0.0, 0.0, 0.0, 0.5) # Black Background gl.glClearDepth(1.0) # Depth Buffer Setup gl.glEnable(gl.GL_DEPTH_TEST) # Enables Depth Testing gl.glDepthFunc(gl.GL_LEQUAL) # The Type Of Depth Testing To Do gl.glEnable(gl.GL_MULTISAMPLE) gl.glEnable(gl.GL_LIGHTING) gl.glEnable(gl.GL_LIGHT0) gl.glHint(gl.GL_PERSPECTIVE_CORRECTION_HINT, gl.GL_NICEST) gl.glEnable(gl.GL_CULL_FACE) gl.glCullFace(gl.GL_BACK) gl.glFrontFace(gl.GL_CCW) gl.glEnable(gl.GL_TEXTURE_2D) # Enable Texture Mapping gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST)
def __init__(self, width, height, caption, resizable=False): pyglet.window.Window.__init__(self, width=width, height=height, caption=caption, resizable=resizable) # sets the background color gl.glClearColor(*black) # pre-loaded models self.model_names = ['box.obj', 'uv_sphere.obj', 'Rigged Hand.obj'] self.models = [] for name in self.model_names: self.models.append( OBJModel((0, 0, -3.5), color=dark_gray, path=name)) # current model self.model_index = 0 self.current_model = self.models[self.model_index] @self.event def on_resize(width, height): # sets the viewport gl.glViewport(0, 0, width, height) # sets the projection gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() glu.gluPerspective(60.0, width / float(height), 0.1, 100.0) # sets the model view gl.glMatrixMode(gl.GL_MODELVIEW) gl.glLoadIdentity() return pyglet.event.EVENT_HANDLED @self.event def on_draw(): # clears the screen with the background color gl.glClear(gl.GL_COLOR_BUFFER_BIT) # sets wire-frame mode gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_LINE) # draws the current model self.current_model.draw() @self.event def on_key_press(symbol, modifiers): # press the LEFT or RIGHT key to change the current model if symbol == pyglet.window.key.RIGHT: # next model self.model_index = (self.model_index + 1) % len( self.model_names) self.current_model = self.models[self.model_index] elif symbol == pyglet.window.key.LEFT: # previous model self.model_index = (self.model_index - 1) % len( self.model_names) self.current_model = self.models[self.model_index] @self.event def on_mouse_scroll(x, y, scroll_x, scroll_y): # scroll the MOUSE WHEEL to zoom self.current_model.z -= scroll_y / 10.0 @self.event def on_mouse_drag(x, y, dx, dy, button, modifiers): # press the LEFT MOUSE BUTTON to rotate if button == pyglet.window.mouse.LEFT: self.current_model.ry += dx / 5.0 self.current_model.rx -= dy / 5.0 # press the LEFT and RIGHT MOUSE BUTTONS simultaneously to pan if button == pyglet.window.mouse.LEFT | pyglet.window.mouse.RIGHT: self.current_model.x += dx / 100.0 self.current_model.y += dy / 100.0
def __init__(self, swarms, coords, models, rnd_att, background_color=sky): # turn off attractor rendering self.render_attractors = rnd_att # original copies of each type of model self.models = models self.swarms = swarms self.cubes = set() for swarm in swarms: self.cubes.add(swarm.cube) # stigmergy setup: if swarms[0].boids: # this line is purely so it is possible to view the attractors on their own if desired self.num_leading_boids = len(swarms[0].boids) self.num_dims = len(swarms[0].boids[0].location) self.leads = [zeros(self.num_dims, dtype=float64)]*self.num_leading_boids # make the objects for the cube self.boxes = [] for cube in self.cubes: if SP.BOUNDING_SPHERE: box_model = deepcopy(self.models[SPHERE]) else: box_model = deepcopy(self.models[BOX]) box_model.x, box_model.y, box_model.z = list(cube.centre)[:3] box_model.color = red # doesn't matter cos not filled in box_model.scale = cube.edge_length/2 self.boxes.append(box_model) self.swarm_models = [] for swarm in self.swarms: colour = rand_colour() # boid_size = (swarm.cube.edge_length/2) * 0.02 # fixed sizes boid_size = 0.5 attractor_size = boid_size * 0.2 boid_models = [] for boid in swarm.boids: boid_model = deepcopy(self.models[PYRAMID]) boid_model.x, boid_model.y, boid_model.z = list(boid.location)[:3] boid_model.color = colour boid_model.scale = boid_size boid_models.append(boid_model) attr_models = [] if self.render_attractors: for attr in swarm.attractors: attractor_model = deepcopy(self.models[BOX]) attractor_model.x, attractor_model.y, attractor_model.z = list(attr.location)[:3] attractor_model.color = colour attractor_model.scale = attractor_size attr_models.append(attractor_model) self.swarm_models.append((boid_models, attr_models)) # sets the background color gl.glClearColor(*background_color) # where the camera starts off: [self.x, self.y, self.z] = coords # rotation values self.rx = self.ry = self.rz = 0 self.cx, self.cy, self.cz = 0, 0, 0
def init(): gl.glClearColor(1, 1, 1, 1)
def on_draw(self): gl.glClearColor(*background_color) ProgressWindow.clear(self) self.label.draw()
def on_draw(self): # ######################################################################### self.label = pyglet.text.Label('QA submission', font_name='Helvetica', font_size=30, x=self.width // 2, y=self.height // 2, anchor_x='center', anchor_y='center', height=self.height, color=(0, 147, 199, 255)) # lets see how much space is left in the window remaining_space = [6.5 * self.height / 8, 0] # divide that by the total number of tests spacing = (remaining_space[0] - remaining_space[1]) / len(unique_tests) count = 0 # set parent tests along the left column, if child tests are present display them next to the parents for item in unique_tests: self.unique_test_labels.append(pyglet.text.Label(item, font_name='Helvetica', font_size=12, x=self.width / 7, y=remaining_space[0] - count * spacing, anchor_x='center', anchor_y='center', color=(0, 147, 199, 255))) if len(organized_tests[item]) > 1: x_spacing = (self.width - 2 * self.width / 7) / \ len(organized_tests[item]) x_count = 0 for child in sorted(organized_tests[item]): self.child_test_labels.append(pyglet.text.Label(child, font_name='Helvetica', font_size=8, x=2 * self.width / 7 + x_count * x_spacing, y=remaining_space[0] - count * spacing, anchor_x='center', anchor_y='center', color=(0, 147, 199, 255))) x_count += 1 green = pyglet.image.load('green.png') green.width = int(self.width / 7) green.height = int(spacing - 2) # print remaining_space[0] temp_sprite = pyglet.sprite.Sprite(green, x=self.width / 7 / 2, y=remaining_space[0] - count * spacing - 0.5 * spacing) temp_sprite.visible = False self.unique_test_sprites.append([temp_sprite, temp_sprite.position, [temp_sprite.x + temp_sprite.width, temp_sprite.y + temp_sprite.height], item]) [a.append(False) for a in self.tests_to_submit] count += 1 # ###################################################### gl.glClearColor(*background_color) Window.clear(self) self.label.draw() [l[0].draw() for l in self.unique_test_sprites] [l[0].draw() for l in self.machine_sprites] [l[0].draw() for l in self.button_sprites] [l.draw() for l in self.machineLabels] [l.draw() for l in self.unique_test_labels] [l.draw() for l in self.child_test_labels] self.vertex_list.draw(pyglet.gl.GL_LINES)
import pyglet import pymunk from pyglet.gl import gl from pymunk import Vec2d from pyglet.window import key from ai import ai from game import player # colors background_color = (.0, .0, .0, 1) game_window = pyglet.window.Window(1360, 768) gl.glClearColor(*background_color) static_lines = [] main_batch = pyglet.graphics.Batch() keys = key.KeyStateHandler() game_window.push_handlers(keys) speed_label = pyglet.text.Label(text="Speed: 0", x=10, y=750, batch=main_batch) xy_label = pyglet.text.Label(text="Position: ", x=10, y=730, batch=main_batch) mode_label = pyglet.text.Label(text="Manual mode", x=10, y=710, batch=main_batch) is_AI = False counter = pyglet.window.FPSDisplay(window=game_window) space = pymunk.Space() space.gravity = Vec2d(0.0, 0.0) player_ship = None event_stack_size = 0
def start(self): def update(dt, batch): distance = player_car.getDistance() speed = player_car.getSpeed() rotationspeed = player_car.getRotationSpeed() rotation = player_car.getRotation() action = RL.choose_action("d:{},s:{},rs:{},r:{}".format( str(round(distance, 0)), str(round(speed, 0)), str(round(rotationspeed, 0)), str(round(rotation, 0)))) player_car.action(action) for obj in game_objects: obj.update(dt, batch) player_car.actionreset() reward = player_car.getScore() - self.score self.score = player_car.getScore() print("{} -- {}".format(action, reward)) _distance = player_car.getDistance() _speed = player_car.getSpeed() _rotationspeed = player_car.getRotationSpeed() _rotation = player_car.getRotation() if (distance > 100 or reward > 10): player_car.reset(200, 200) else: done = False RL.learn( "d:{},s:{},rs:{},r:{}".format(str(round(distance, 0)), str(round(speed, 0)), str(round(rotationspeed, 0)), str(round(rotation, 0))), action, reward, "d:{},s:{},rs:{},r:{}".format(str(round(_distance, 0)), str(round(_speed, 0)), str(round(_rotationspeed, 0)), str(round(_rotation, 0)))) def updateh(dt, batch): for obj in game_objects: obj.update(dt, batch) def updatel(dt, batch): if (self.r != True): learn(dt, batch) self.r = True else: print("E") def learn(dt, batch): for episode in range(100): player_car.reset(200, 200) distance = player_car.getDistance() speed = player_car.getSpeed() done = False while True: action = RL.choose_action(str(distance)) player_car.action(action) update(1 / 144, batch) player_car.actionreset() reward = player_car.getScore() + -1 * ( player_car.getDistance() / 100.0) * .5 _distance = player_car.getDistance() _speed = player_car.getSpeed() if (distance > 1000 or reward > 10): done = True else: done = False print(action) print(distance) print(reward) RL.learn(str(distance), action, reward, str(_distance)) distance = _distance speed = _speed if done: break pyglet.resource.path = ['resources'] pyglet.resource.reindex() #game_window = pyglet.window.Window() game_window = pyglet.window.Window(width=1280, height=720) gl.glClearColor(.25, .25, .25, 1) batch = pyglet.graphics.Batch() car_image = pyglet.resource.image("car.png") center_image(car_image) score_label = pyglet.text.Label(text="Rotations: 0", x=10, y=575, batch=batch) distance_label = pyglet.text.Label(text="Distance: 0", x=10, y=555, batch=batch) speed_label = pyglet.text.Label(text="Speed: 0", x=10, y=535, batch=batch) rotationspeed_label = pyglet.text.Label(text="Rotation Speed: 0", x=10, y=515, batch=batch) direction_label = pyglet.text.Label(text="Direction: 0", x=10, y=495, batch=batch) fps_label = pyglet.text.Label(text="fps: 0", x=10, y=475, batch=batch) player_car = Car(img=car_image, x=200, y=200, batch=batch) player_car.scale = CAR_SIZE game_window.push_handlers(player_car) game_objects = [player_car] @game_window.event def on_draw(): game_window.clear() batch.draw() score_label.text = "Rotations: {}".format(player_car.getScore()) distance_label.text = "Distance: {}".format( player_car.getDistance()) speed_label.text = "Speed: {}".format(player_car.getSpeed()) direction_label.text = "Direction: {}".format( player_car.getRotation()) rotationspeed_label.text = "Rotation Speed: {}".format( player_car.getRotationSpeed()) try: fps_label.text = "fps: {}".format(1 / player_car.getDT()) except: pass RL = ql.QLearningTable(actions=['u', 'd', 'l', 'r', 'n']) pyglet.clock.schedule_interval(update, 1 / 144.0, batch) #pyglet.clock.schedule_once(learn,1/144.0,batch) pyglet.app.run()
def init(): gl.glClearColor(0.9, 0.9, 0.9, 1.0) gl.glClear(gl.GL_COLOR_BUFFER_BIT)
import pyglet from pyglet.window import key from pyglet.gl import gl # colors on_colour = (0, .5, .8, 1) off_colour = (0.5, 0, 0.8, 1) window = pyglet.window.Window(width=300, height=300, caption='Press key/button to start') window.set_fullscreen(True) # sets the background color gl.glClearColor(*off_colour) window.clear() boat = pyglet.media.load("audio_tracks\\Boat_Amie.wav", streaming=False) player = pyglet.media.Player() player.queue(boat) player.EOS_LOOP = 'loop' firston = False @window.event def on_key_press(symbol, modifiers): global firston if symbol == key.R: print('Repeat play') boat.play()