Пример #1
0
 def generate_mosaic(self, target, dims, blur, out, vtype, frate=16):
     """
     Generates and writes video mosaic.
     """
     writer = cv2.VideoWriter(out, cv2.VideoWriter_fourcc('X', 'V', 'I', 'D'),
                              frate, (dims[1], dims[0]))
     reader = cv2.VideoCapture(target)
     success, image = reader.read()
     count = 0
     texturize = None
     while success:
         print('Reading target frame ' + str(count))
         frame = resize_image(image, dims)
         print('Generating output frame ' + str(count))
         if vtype == 'mosaic':
             out_frame = np.zeros(frame.shape)
             for row in range(self.tile_size, dims[0] + 1, self.tile_size):
                 for col in range(self.tile_size, dims[1] + 1, self.tile_size):
                     region = frame[row - self.tile_size:row, col - self.tile_size:col]
                     best = self.tiles[self.good_match(region), ...]
                     out_frame[row - self.tile_size:row, col - self.tile_size:col, :] = best
         elif vtype == 'texture':
             if texturize is None:
                 texturize = Texture((dims[0], dims[1], 3), 25)
                 texturize.set_candidates(self.tiles, 3, True)
             out_frame = texturize.gen_texture(None, frame, 3, .5)
         if blur:
             out_frame = cv2.GaussianBlur(out_frame, (21, 21), 0)
         writer.write(np.uint8(out_frame))
         success, image = reader.read()
         count += 1
     reader.release()
     writer.release()
Пример #2
0
class SimpleScreen(Screen):
  """A screen with a single textured quad displaying a background image"""

  def __init__(self, ui, textureFile):
    super(SimpleScreen, self).__init__(ui)
    self._texture = Texture(textureFile)

  def draw(self):
    """Draw the menu background"""
    # Clear the screen
    glClearColor(0, 0, 0, 1)
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    glEnable(GL_TEXTURE_2D)

    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()

    self._texture.bind()
    glBegin(GL_QUADS)
    if True:
      glColor4f(1, 1, 1, 1)
      glTexCoord2f(0.0, 0.0); glVertex2f(-8.0, -6.0)
      glTexCoord2f(1.0, 0.0); glVertex2f( 8.0, -6.0)
      glTexCoord2f(1.0, 1.0); glVertex2f( 8.0,  6.0)
      glTexCoord2f(0.0, 1.0); glVertex2f(-8.0,  6.0)
    glEnd()
Пример #3
0
    def __init__(self):
        # feel free to move this up in the viewer as per other practicals
        self.shader = Shader(TEXTURE_VERT, TEXTURE_FRAG)

        # triangle and face buffers
        vertices = np.array(((7, 9, 0), (10, 9, 0), (10, 10, 0), (7, 10, 0)),
                            np.float32)
        faces = np.array(((0, 1, 2), (0, 2, 3)), np.uint32)
        self.vertex_array = VertexArray(
            [vertices, [(0, 0), (-1, 0), (-1, -1), (0, -1)]], faces)

        # interactive toggles
        self.wrap = cycle([
            GL.GL_REPEAT, GL.GL_MIRRORED_REPEAT, GL.GL_CLAMP_TO_BORDER,
            GL.GL_CLAMP_TO_EDGE
        ])
        self.filter = cycle([(GL.GL_NEAREST, GL.GL_NEAREST),
                             (GL.GL_LINEAR, GL.GL_LINEAR),
                             (GL.GL_LINEAR, GL.GL_LINEAR_MIPMAP_LINEAR)])
        self.wrap_mode, self.filter_mode = next(self.wrap), next(self.filter)

        # setup texture and upload it to GPU
        self.textures = {
            "CLEAR":
            Texture("control/arrows.png", self.wrap_mode, *self.filter_mode),
            "UP":
            Texture("control/arrowsUP.png", self.wrap_mode, *self.filter_mode),
            "LEFT":
            Texture("control/arrowsRIGHT.png", self.wrap_mode,
                    *self.filter_mode),
            "RIGHT":
            Texture("control/arrowsLEFT.png", self.wrap_mode,
                    *self.filter_mode)
        }
        self.texture = self.textures["CLEAR"]
Пример #4
0
def build_texture_from_image(img):
	from texture import Texture
	height, width = img.shape[:2]
	tex = Texture(GL_TEXTURE_2D, 1, GL_RGB8, width, height)

	tex.sub_image(0, 0, 0, width, height, GL_BGR, GL_UNSIGNED_BYTE, img)	
	return tex
Пример #5
0
class SimpleScreen(Screen):
    """A screen with a single textured quad displaying a background image"""
    def __init__(self, ui, textureFile):
        super(SimpleScreen, self).__init__(ui)
        self._texture = Texture(textureFile)

    def draw(self):
        """Draw the menu background"""
        # Clear the screen
        glClearColor(0, 0, 0, 1)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        glEnable(GL_TEXTURE_2D)

        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

        self._texture.bind()
        glBegin(GL_QUADS)
        if True:
            glColor4f(1, 1, 1, 1)
            glTexCoord2f(0.0, 0.0)
            glVertex2f(-8.0, -6.0)
            glTexCoord2f(1.0, 0.0)
            glVertex2f(8.0, -6.0)
            glTexCoord2f(1.0, 1.0)
            glVertex2f(8.0, 6.0)
            glTexCoord2f(0.0, 1.0)
            glVertex2f(-8.0, 6.0)
        glEnd()
Пример #6
0
 def test_resize(self):
     data = np.zeros((10, 10), dtype=np.uint8)
     T = Texture(data=data)
     T.resize((5, 5))
     assert T.shape == (5, 5)
     assert T._data.shape == (5, 5)
     assert T._need_resize == True
     assert T._need_update == False
     assert len(T._pending_data) == 0
Пример #7
0
 def test_resize(self):
     data = np.zeros((10,10), dtype=np.uint8)
     T = Texture(data=data)
     T.resize((5,5))
     assert T.shape == (5,5)
     assert T._data.shape == (5,5)
     assert T._need_resize == True
     assert T._need_update == False
     assert len(T._pending_data) == 0
Пример #8
0
def simple_patches_synthesizer(args):
    print "Using Simple Patches Synthesizer"
    default_texture = Texture()
    default_texture.load_texture(args.input_file)
    patches = default_texture.create_patches(args.patch_height,
                                             args.patch_width)
    new_texture = Texture.create_simple_tex_from_patches(patches,
                                                         args.height,
                                                         args.width)   
    new_texture.save_texture(args.output_file)
    return
Пример #9
0
def mincut_overlap_patches_synthesizer(args):
    print "Using Mincut Overlap Patches Synthesizer"
    default_texture = Texture()
    default_texture.load_texture(args.input_file)
    patches = default_texture.create_patches(args.patch_height,
                                             args.patch_width,
                                             overlap=args.overlap_percent)
    new_texture = Texture.create_mincut_tex_from_patches(patches,
                                                         args.height,
                                                         args.width)
    new_texture.save_texture(args.output_file)
    return 
Пример #10
0
class Menu_log:

#-------------------------------------------------------------------------------------------------------

	def __init__( self ):
		self.text = Text( "menu/KGHAPPY.ttf", 27, 255 )
		self.texture = Texture( "menu/exit.png", 255 )
		self.type = 0

#-------------------------------------------------------------------------------------------------------
	
	def load( self, width, height ):

		self.texture.setX( width/2 - self.texture.getWidth()/2 )
		self.texture.setY( height/2 - self.texture.getHeight()/2 )
		self.texture.setColor( 30, 0, 255 )

		self.text.createText( "m-menu  b-back", [ 0xFF, 0xFF, 0xFF ] )
		self.text.setX( width/2 - self.text.getWidth()/2 )
		self.text.setY( height/2 - self.text.getHeight()/2 )

#-------------------------------------------------------------------------------------------------------
	
	def draw( self, window ):
		if self.type == 1:
			self.texture.draw( window )
			self.text.draw( window )

#-------------------------------------------------------------------------------------------------------

	def getState( self ):
		return self.type

#-------------------------------------------------------------------------------------------------------

	def setState( self, t ):
		self.type = t

#-------------------------------------------------------------------------------------------------------

	def handle( self, event ):

		if event.type == pygame.KEYDOWN:

			if event.key == pygame.K_m:
				if self.type == 0:
					self.type = 1
				elif self.type == 1:
					self.type = 2

			elif event.key == pygame.K_b:
				if self.type == 1:
					self.type = 0
Пример #11
0
	def __init__(self, font_file):
		self._glyphs = {}
		self._kern = {}
		self._page = {}

		if "." not in font_file:
			font_file = font_file+".zip"

		with zipfile.ZipFile(font_file,'r') as z:
			if font_file.lower().endswith(".zip"):
				font_file = os.path.basename(font_file)[:-4]

			xml = z.read(font_file+".fnt")
			xroot = ET.fromstring(xml)
			# misc info
			com = xroot.find('common')
			self._line_height = int(com.get("lineHeight"))
			self._base = int(com.get("base"))
			self._imgw = int(com.get("scaleW"))
			self._imgh = int(com.get("scaleH"))
		

			# load the textures
			for page in xroot.find('pages').findall("page"):
				id = int(page.get("id"))
				img_filename = page.get("file")
				img = z.read(img_filename)
				surf = pygame.image.load(StringIO.StringIO(img),img_filename)
				tex = Texture()
				tex.setFromSurface(surf)
				self._page[id] = tex

				assert(id == 0) # for now, we only support single-page fonts
			
			# load the glyph data
			for char in xroot.find("chars").findall("char"):
				d = {}
				for f in self.Glyph._fields:
					d[f] = int(char.get(f))

				g=self.Glyph(**d)
				self._glyphs[g.id] = g

			# load the kerning data
			for kern in xroot.find("kernings").findall("kerning"):
				t = (int(kern.get("first")), int(kern.get("second")))
				self._kern[t] = int(kern.get("amount"))


		self._material = Material()

		self._material.setTexture(0,self._page[0])
Пример #12
0
	def __init__(self,pos,type):
		self.pos = pos;
		if(type in [1,2]):
			self.texture = Texture(load_texture("obstacles",0 if type == 1 else 1),bg_color = colorama.Back.BLUE,fore_color = colorama.Fore.CYAN);
			self.hitbox = Hitbox(self.pos,Vector2D(3,11));
		if(type in [3,4]):
			self.texture = Texture(load_texture("obstacles",2 if type == 3 else 3),bg_color = colorama.Back.BLUE,fore_color = colorama.Fore.CYAN);
			self.hitbox = Hitbox(self.pos,Vector2D(2,2));
		if(type in [5,6]):
			self.texture = Texture(load_texture("obstacles",4 if type == 5 else 5),bg_color = colorama.Back.BLUE,fore_color = colorama.Fore.CYAN);
			self.hitbox = Hitbox(self.pos,Vector2D(6,2));
		if(type in [7,8]):
			self.texture = Texture(load_texture("obstacles",6 if type == 7 else 7),bg_color = colorama.Back.BLUE,fore_color = colorama.Fore.CYAN,transparent = False);
			self.hitbox = Hitbox(self.pos,Vector2D(7,24));
Пример #13
0
class PointCloud(GLArray):
    def __init__(self, vertex_data=None, color_data=None):
        GLArray.__init__(self, vertex_data, color_data)
        self._sprite_texture = None

    def sprite(self, filename):
        print " -- initializing point sprite {}".format(filename)

        self._sprite_texture = Texture(filename)

    def _pre_draw(self):
        GLArray._pre_draw(self)

        if self._sprite_texture == None:
            return

        glDepthMask(GL_FALSE)

        glEnable(GL_POINT_SMOOTH)
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE)

        self._sprite_texture.bind()

        glTexEnvf(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE)
        glEnable(GL_POINT_SPRITE)

        glPointSize(15.0)

    def _post_draw(self):
        GLArray._post_draw(self)

        if self._sprite_texture == None:
            return

        self._sprite_texture.unbind()

        glDisable(GL_BLEND)
        glDisable(GL_POINT_SPRITE)

    def center(self):
        try:
            return self._center
        except:
            self._center = [0.0, 0.0, 0.0]
            for i in range(3):
                self._center[i] = sum(v[i] for v in self._vertex_data) / len(self._vertex_data)
            return self._center
Пример #14
0
	def __init__(self,pos,texture, **kwargs):
		self.pos = pos;
		transparent = kwargs.get("transparent",True);
		fore_color = kwargs.get("fore_color",colorama.Fore.WHITE)
		style = kwargs.get("style",colorama.Style.NORMAL)
		bg_color = kwargs.get("bg_color",colorama.Back.BLACK)
		self.texture = Texture(texture,fore_color = fore_color,bg_color = bg_color,style = style,transparent = transparent);
Пример #15
0
    def test_setitem_single(self):

        data = np.zeros((10,10), dtype=np.uint8)
        T = Texture(data=data)
        T[0,0] = 1
        assert len(T._pending_data) == 2
        assert data[0,0] == 1,1
Пример #16
0
    def merge_textures(self, data):
        """
        data: A list of (id, height) tuples.
        """
        texturesToMerge = []
        for id, height in data:
            if id <= 0:
                continue
            texture = self.textures.get(id)
            if texture is None:
                continue
            texturesToMerge.append((height, texture))

        if not texturesToMerge:
            return None
        rects = [
            pg.Rect((-t.xoff, -t.yoff - height), t.image.get_size())
            for height, t in texturesToMerge
        ]
        rect = rects[0].unionall(rects)
        image = utils.new_surface(rect.size)
        # image.fill((0x50, 0x50, 0x50, 100))
        x, y = -rect.x, -rect.y
        for height, t in texturesToMerge:
            image.blit(t.image, (x - t.xoff, y - t.yoff - height))
        return Texture(x, y, image)
Пример #17
0
class Laser:
    dmg = 0
    speed = 10
    direction = 0
    pos = Vector2D(0, 0)
    hitbox = None
    texture = Texture("─" * 10,
                      fore_color=colorama.Fore.RED,
                      style=colorama.Style.BRIGHT)

    #constructor übergibt shaden position sowie richtung des lasers
    def __init__(self, pos, dmg, dir):
        self.dmg = dmg
        self.direction = dir

        self.pos = pos

        if (self.direction == 0):
            self.hitbox = Hitbox(self.pos, Vector2D(10, 2))
        else:
            self.hitbox = Hitbox(self.pos, Vector2D(10, 0))

        if (self.dmg >= 5):
            self.texture.texture = "=" * 10
        else:
            self.texture.texture = "─" * 10

    #updated shuss position
    def update(self):
        if (self.direction == 0):
            self.pos.x += self.speed
            self.hitbox.update_pos(Vector2D(self.pos.x - 10, self.pos.y - 1))
        else:
            self.hitbox.update_pos(Vector2D(self.pos.x, self.pos.y))
            self.pos.x -= self.speed
Пример #18
0
 def __init__(self, imageId, major_axis, minor_axis, speed, rot_speed, size, textureMoon=None, moonOrbitParams=None):
     self.texture = Texture(imageId)
     self.qobj = gluNewQuadric()
     gluQuadricTexture(self.qobj, GL_TRUE)
     self.ellipse = Ellipse(major_axis, minor_axis, speed)
     self.rotation = 0
     self.lastCoords = 0
     self.rot_speed = rot_speed
     self.size = size
     if(textureMoon is None):
         self.moon = False
     else:
         self.moon = True
         self.textureMoon = Texture(textureMoon)
         self.moonSize = moonOrbitParams[2]
         self.moonOrbit = Ellipse(moonOrbitParams[0], moonOrbitParams[0], moonOrbitParams[1])
Пример #19
0
def render_moon(scene):

    light = Light(Color(1.0, 1.0, 1.0, 1.0), 1.0)
    light.transform.position = Vector3(0.0, 2.0, -2.0)
    scene.set_light(light)

    lambertianTintMaterial = Material()
    lambertianTintMaterial.albedo = Color(1.0, 1.0, 1.0, 1.0)
    lambertianTintMaterial.shader = LambertianTintShader()

    s1_earth = Sphere(0.6)
    s1_earth.transform.position = Vector3(0, 0, 1.5)
    s1_earth.material = lambertianTintMaterial.clone()
    scene.add_objects(s1_earth)

    s2_moon = Sphere(0.4)
    s2_moon.transform.position = Vector3(-0.2, -0.5, 1.2)
    s2_moon.material = lambertianTintMaterial.clone()
    s2_moon.material.set_texture(Texture("images/moon.jpg"))
    scene.add_objects(s2_moon)

    v1 = Vector3(0.0, 1.5, 0.5)
    v2 = Vector3(0.5, -1.0, 0.0)
    animation_velocity = 0.4

    def update_method(t):
        p = Vector3(-0.2, -0.5, 1.2)
        p = p.add(v1.multiply(np.cos(animation_velocity * t * np.pi)))
        p = p.add(v2.multiply(np.sin(animation_velocity * t * np.pi)))

        s2_moon.transform.position = p
        s2_moon.transform.rotation = Vector3(
            0.0, np.mod(0.5 * animation_velocity * t, 360), 0.0)

    return update_method
Пример #20
0
    def __init__(self, name, strategy, radius, latitudes, longitudes, rotation_speed, central_body, mass,
                 textureimage, longitude_of_the_ascending_node, argument_of_the_perihelion, inclination_to_ecliptic,
                 periapsis=0., apoapsis=0., angle=1.0):
        """
        Sets all the necessary attributes.
        """
        self.original_radius = radius
        self.name = name
        self.strategy = strategy
        self.position = BetterVector(periapsis, 0, 0)
        self.radius = radius
        self.latitudes = latitudes
        self.longitudes = longitudes
        self.rotation_speed = rotation_speed / 365 / 24 / 60 / 60
        self.central_body = central_body
        self.rotation = 0
        self.mass = mass
        self.textureimage = textureimage
        self.angle = angle
        self.periapsis = periapsis
        self.apoapsis = apoapsis
        self.texture = Texture(self.textureimage)
        self.sphere = gluNewQuadric()
        self.calc_speed()
        self.longitude_of_the_ascending_node = longitude_of_the_ascending_node
        self.argument_of_the_perihelion = argument_of_the_perihelion
        self.inclination_to_ecliptic = inclination_to_ecliptic
        self.is_real = False
        self.time = 0
        self.showTexture = True
        self.speed = 0

        gluQuadricNormals(self.sphere, GLU_SMOOTH)
        gluQuadricTexture(self.sphere, GL_TRUE)
Пример #21
0
	def __init__( self ):

		self.core = Core( 60, 1024, 768, "Ninja" )

		self.intro = Intro()

		self.menu_background = Texture( "menu/background.png" )
		self.menu_title = Menu_title()
		self.menu_play_button = Menu_play_button()
		self.menu_git_button = Menu_link_button( "menu/git.png", "https://github.com/Adriqun" )
		self.menu_google_button = Menu_link_button( "menu/google.png", "https://en.wikipedia.org/wiki/Ninja" )
		self.menu_facebook_button = Menu_link_button( "menu/facebook.png", "nothing", True )
		self.menu_twitter_button = Menu_link_button( "menu/twitter.png", "nothing", True )
		self.menu_music_button = Menu_music_button( "menu/music.png" )
		self.menu_chunk_button = Menu_music_button( "menu/chunk.png", 1 )
		self.menu_exit_log = Menu_exit_log()
		self.menu_author_log = Menu_author_log()
		self.menu_game_log = Menu_link_button( "menu/game.png", "nothing", True )
		self.menu_settings_log = Menu_link_button( "menu/settings.png", "nothing", True )
		self.menu_score_log = Menu_score_log()
		self.menu_music = Menu_music( "menu/Rayman Legends OST - Moving Ground.mp3" )
		
		self.wall = Wall()
		self.hero = Hero()
		self.menu_log = Menu_log()
		self.map = Map()
Пример #22
0
    def load_textured(self, tex_file=None):

        # Note: embedded textures not supported at the moment
        path = os.path.dirname(
            self.file) if os.path.dirname(self.file) != '' else './'
        for mat in self.scene.mMaterials:
            if not tex_file and 'TEXTURE_BASE' in mat.properties:  # texture token
                name = os.path.basename(mat.properties['TEXTURE_BASE'])
                # search texture in file's whole subdir since path often screwed up
                paths = os.walk(path, followlinks=True)
                found = [
                    os.path.join(d, f) for d, _, n in paths for f in n
                    if name.startswith(f) or f.startswith(name)
                ]
                assert found, 'Cannot find texture %s in %s subtree' % (name,
                                                                        path)
                tex_file = found[0]
            if tex_file:
                mat.properties['diffuse_map'] = Texture(tex_file=tex_file)

        # prepare textured mesh
        meshes = []
        for mesh in self.scene.mMeshes:
            mat = self.scene.mMaterials[mesh.mMaterialIndex].properties
            assert mat[
                'diffuse_map'], "Trying to map using a textureless material"
            attributes = [mesh.mVertices, mesh.mTextureCoords[0]]
            mesh = TexturedMesh(self.shader, mat['diffuse_map'], attributes,
                                mesh.mFaces)
            meshes.append(mesh)

        size = sum((mesh.mNumFaces for mesh in self.scene.mMeshes))
        print('Loaded %s\t(%d meshes, %d faces)' %
              (self.file, len(meshes), size))
        return meshes
Пример #23
0
    def update_display(self):
        if (self.dxxoffset != 0):
            self.update_center()
        self.screen.blit(self.background, self.rect)
        self.draw_road((self.road_height), self.road_pos,
                       (GREEN, RED, GRAY, WHITE))

        # Update count for each frame, every 2 frames add a new texture to Queue
        self.texture_count += 1
        if (self.texture_count > TEXTURE_DIFFERENCE):
            texture = Texture()
            self.textures.insert(0, texture)
            self.texture_count = 0

        self.update_textures()
        self.update_props()

        self.player_rect = pygame.Rect((self.pos[0] - 25) * 2,
                                       self.player_height, 96, 70)
        # Player hitbox:
        #pygame.draw.rect(self.screen, RED, self.player_rect)
        self.screen.blit(self.player, self.player_rect)
        self.player = self.player_images[0]  # reset car to straight position

        self.update_obstacles()

        score = 'SCORE:%d' % self.score
        self.draw_word(score, self.width - 100, TEXT_HEIGHT, (YELLOW, BLACK),
                       True)
        highscore = 'HIGHSCORE:%d' % self.highscore
        self.draw_word(highscore, 120, TEXT_HEIGHT, (YELLOW, RED), True)

        pygame.display.flip()
Пример #24
0
    def test_setitem_all_no_store(self):

        data = np.zeros((10,10), dtype=np.uint8)
        T = Texture(data=data, store=False)
        T[...] = np.ones((10,10))
        assert len(T._pending_data) == 1
        assert np.allclose(data,np.zeros((10,10)))
Пример #25
0
    def test_setitem_partial(self):

        data = np.zeros((10,10), dtype=np.uint8)
        T = Texture(data=data)
        T[5:,5:] = 1
        assert len(T._pending_data) == 2
        assert np.allclose(data[5:,5:], np.ones((5,5)))
Пример #26
0
def generate_textures(seeds, dims, out_dir, window=None, rotate=3):
    """
    Computes textures from intentionally distorted warp triangles.

    Args:
        faces (list): A list of images representing faces.
        dims (tuple): Desired dimensions of output image.
        out_dir (str): Directory to save textures to.
    """
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)

    textures = []
    for num, seed in enumerate(seeds):
        try:
            if not window:
                if min(seed.shape[:2]) > 50:
                    w_size = int(min(seed.shape[:2]) * .5)
                else:
                    w_size = int(min(seed.shape[:2]) * .75)
            else:
                w_size = window
            if w_size % 2 == 0:
                w_size -= 1
            texture = Texture(dims, w_size).get_texture(seed, None, rotate)
            out_path = os.path.join(out_dir, 'texture{0:04d}.png'.format(num))
            cv2.imwrite(out_path, texture)
            textures.append(texture)
        except KeyboardInterrupt:
            continue
    return textures
Пример #27
0
    def __init__(self, filename):
        texture = Texture(filename)

        # A CharacterSet font image is 16 characters by 16 characters
        charw = texture.w / 16
        charh = texture.h / 16

        super(CharacterSet, self).__init__(texture, charw, charh)
Пример #28
0
 def __init__(self, pos, path):
     self.path = []
     self.laser = []
     self.path = get_path(path)
     self.pos = pos
     self.texture = Texture(load_texture("entity", 6),
                            fore_color=colorama.Fore.CYAN)
     self.hitbox = Hitbox(pos, Vector2D(6, 5))
Пример #29
0
 def __init__(self, app, texture_filename=None, image_data=None):
     self.app = app
     self.unique_name = '%s_%s' % (int(
         time.time()), self.__class__.__name__)
     self.x, self.y, self.z = self.get_initial_position()
     self.scale_x, self.scale_y, self.scale_z = self.get_initial_scale()
     if self.app.use_vao:
         self.vao = GL.glGenVertexArrays(1)
         GL.glBindVertexArray(self.vao)
     # support loading texture from file or from provided data
     # (remember the filename for later use)
     if texture_filename:
         self.texture_filename = texture_filename
     if not image_data:
         image_data = Image.open(self.texture_filename)
     image_data = image_data.convert('RGBA')
     if self.flip_y:
         image_data = image_data.transpose(Image.FLIP_TOP_BOTTOM)
     w, h = image_data.size
     self.texture = Texture(image_data.tobytes(), w, h)
     self.shader = self.app.sl.new_shader(self.vert_shader_source,
                                          self.frag_shader_source)
     self.proj_matrix_uniform = self.shader.get_uniform_location(
         'projection')
     self.view_matrix_uniform = self.shader.get_uniform_location('view')
     self.position_uniform = self.shader.get_uniform_location(
         'objectPosition')
     self.scale_uniform = self.shader.get_uniform_location('objectScale')
     self.tex_uniform = self.shader.get_uniform_location('texture0')
     self.tex_scale_uniform = self.shader.get_uniform_location('texScale')
     self.alpha_uniform = self.shader.get_uniform_location('alpha')
     self.vert_buffer = GL.glGenBuffers(1)
     GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.vert_buffer)
     GL.glBufferData(GL.GL_ARRAY_BUFFER, self.vert_array.nbytes,
                     self.vert_array, GL.GL_STATIC_DRAW)
     self.vert_count = 4
     self.pos_attrib = self.shader.get_attrib_location('vertPosition')
     GL.glEnableVertexAttribArray(self.pos_attrib)
     offset = ctypes.c_void_p(0)
     GL.glVertexAttribPointer(self.pos_attrib, 2, GL.GL_FLOAT, GL.GL_FALSE,
                              0, offset)
     GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
     if self.app.use_vao:
         GL.glBindVertexArray(0)
     self.texture.set_wrap(self.tex_wrap)
Пример #30
0
    def __init__(self, screen_size: tuple, screen_pos: tuple=(0, 0),
                 game_mode: bool=False, title: str='Default Title', **params):
        width, height = screen_size
        self.screen_size = screen_size
        self.screen_pos = screen_pos
        self.width = width
        self.height = height
        self.z_near = 1.0
        self.z_far = 100.0
        self.fov = 60.0
        self.game_mode = game_mode
        self.title = title

        self._vbo = None
        self._vao = None
        self._ibo = None
        self._program = None
        self._texture = None
        self._vertices = None
        self._indexes = None
        self._camera = None
        self._pipeline = None
        self._scale = 0.0
        self._dir_light_color = 1.0, 1.0, 1.0
        self._dir_light_ambient_intensity = 0.5
        self._projection = ProjParams(
            self.width, self.height, self.z_near, self.z_far, self.fov)

        self._log = params.get("log", print)
        self._clear_color = params.get("clearcolor", (0, 0, 0, 0))
        self._vertex_attributes = {"Position": -1, "TexCoord": -1}

        self._init_glut()
        self._init_gl()
        self._create_vertex_buffer()
        self._create_index_buffer()

        self._effect = LightingTechnique("shaders/vs.glsl", "shaders/fs_lighting.glsl")
        self._effect.init()
        self._effect.enable()
        self._effect.set_texture_unit(0)

        self._texture = Texture(GL_TEXTURE_2D, "resources/test.png")
        if not self._texture.load():
            raise ValueError("cannot load texture")
Пример #31
0
	def __init__( self ):

		self.sprite = Sprite( "menu/position.png", 4 )
		self.window = Texture( "menu/window.png" )
		self.click = pygame.mixer.Sound( "menu/click.wav" )

		self.on = 0
		self.type = 0
		self.text = Text( "menu/KGHAPPY.ttf", 30 )
Пример #32
0
 def __init__(self):
     self.gns = GNS()
     self.situation = None
     self.texture_files = None
     self.resource_files = None
     self.texture = Texture_File()
     self.resources = Resources()
     self.extents = None
     self.hypotenuse = None
Пример #33
0
 def open(self):
     file_name, _ = QFileDialog.getOpenFileName(
         self, 'Open image',
         os.path.join(QDir.currentPath(), Texture.get_textures_folder()))
     if file_name and self.palette:
         self.last_image = TextureBuilder().get_texture(file_name)
         self.scale_factor = 1.0
         self.update_image()
         self.update_actions()
Пример #34
0
    def test_getitem_setitem(self):

        data = np.zeros((10,10), dtype=np.uint8)
        T = Texture(data=data)
        Z = T[5:,5:]
        Z[...] = 1
        assert len(Z._pending_data) == 0
        assert len(T._pending_data) == 2
        assert np.allclose(data[5:,5:], np.ones((5,5)))
Пример #35
0
 def get(self, image):
     if isinstance(image, Texture):
         return image
     if image in self.cache:
         return self.cache[image]
     else:
         self.cache[image] =texture= Texture.empty(image.width, image.height)
         texture.upload(image.data)
         return texture
Пример #36
0
def main():
    # Will use GLUT https://compgraphics.info/OpenGL/template_glut.php,
    # but on Python https://wiki.python.org/moin/PyOpenGL

    obj_file = ObjLoader(f"models/{Config.model}.obj")

    glutInit(sys.argv)
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH)
    glutInitWindowSize(Config.width, Config.height)
    glutCreateWindow("HW2, Object, Tankov Vladislav")

    Program.prepare(obj_file.prepared_vertices, obj_file.prepared_normals)

    Program.create()
    # forward tex coord to fragment
    Program.attach_shader(
        Shader.load("shader/vertex_noise.glsl", GL_VERTEX_SHADER))
    # apply noise
    Program.attach_shader(
        Shader.load("shader/fragment_noise.glsl", GL_FRAGMENT_SHADER))
    Program.link()

    Texture.create_2d(obj_file.prepared_tex_coords)

    Program.use()

    Camera.update_gl()
    Lightning.update_gl()

    glutDisplayFunc(Display.display(obj_file.prepared_vertices))
    glutReshapeFunc(Display.reshape)

    glutIdleFunc(Display.idle)

    glutMouseFunc(Controls.mouse)
    glutMotionFunc(Controls.motion)

    glutCreateMenu(Controls.menu)
    glutAddMenuEntry("Disable Dissolve", 0)
    glutAddMenuEntry("Enable Dissolve", 1)
    glutAttachMenu(GLUT_RIGHT_BUTTON)

    glutMainLoop()
Пример #37
0
    def test_getitem_single(self):

        data = np.zeros((10,10,10), dtype=np.uint8)
        T = Texture(data=data)
        Z = T[0,0,0]
        assert Z._base is T
        assert Z._data.base is T._data
        assert Z._shape == (1,1,1)
        assert Z._resizeable == False
        assert len(Z._pending_data) == 0
Пример #38
0
def init_gl():
    global obj
    global cam
    global sun
    global mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
    global planets
    global asteroid
    global t
    global quad
    global ship

    glClearColor(0.0, 0.0, 0.0, 1.0)
    glClearDepth(1.0)
    glEnable(GL_DEPTH_TEST)
    glShadeModel(GL_SMOOTH)

    glEnable(GL_LIGHTING)

    glLightfv(GL_LIGHT0, GL_AMBIENT, light_amb_0)
    glLightfv(GL_LIGHT0, GL_POSITION, light_pos_0)
    glEnable(GL_LIGHT0)

    glLightfv(GL_LIGHT1, GL_POSITION, light_pos_1)
    glLightfv(GL_LIGHT1, GL_SPOT_DIRECTION, light_dir_1)
    glLightfv(GL_LIGHT1, GL_AMBIENT, light_amb_1)
    glLightfv(GL_LIGHT1, GL_DIFFUSE, light_dif_1)
    glEnable(GL_LIGHT1)

    obj = OBJ("cube.obj", textureFile="stars.jpg")
    obj.generate()

    cam = Camera()

    sun = Sun(textureFile="sun.jpg")

    mercury = Planet("mercury.jpg", 8, 5, 0.5, 0.1, 0.25)
    venus = Planet("venus.jpg", 9.6, 6, 0.4, 0.1, 0.35)
    earth = Planet("earth.jpg", 11.2, 7, 0.3, 0.1, 0.45, "moon.jpg",
                   [0.7, 0.8, 0.09])
    mars = Planet("mars.jpg", 12.8, 8, 0.2, 0.1, 0.33)
    jupiter = Planet("jupiter.jpg", 19.2, 12, 0.2, 1, 1.5, "jupiter-moon.jpg",
                     [3, 1, 0.3])
    saturn = Planet("saturn.jpg", 25.6, 16, 0.15, 0.2, 1.1)
    uranus = Planet("uranus.jpg", 30.4, 19, 0.11, 0.2, 0.8)
    neptune = Planet("neptune.jpg", 32.8, 20.5, 0.09, 0.2, 0.7)
    planets = [mercury, venus, earth, mars, jupiter, saturn, uranus, neptune]

    quad = gluNewQuadric()
    gluQuadricTexture(quad, GL_TRUE)

    asteroid = Asteroid(Fire())

    t = Texture("rings.jpg")

    ship = pywavefront.Wavefront('Apollo/apollo.obj')
Пример #39
0
 def test_init_dtype(self):
     T = Texture(dtype=np.uint8)
     assert T._shape == ()
     assert T._dtype == np.uint8
     assert T._offset == ()
     assert T._store == True
     assert T._copy == False
     assert T._need_resize == False
     assert T._need_update == False
     assert T._data is not None
     assert len(T._pending_data) == 0
Пример #40
0
    def test_getitem_partial(self):

        data = np.zeros((10,10), dtype=np.uint8)
        T = Texture(data=data)
        Z = T[2:5,2:5]
        assert Z._base is T
        assert Z._data.base is T._data
        assert Z._shape == (3,3)
        assert Z._offset == (2,2)
        assert Z._resizeable == False
        assert len(Z._pending_data) == 0
Пример #41
0
	def __init__( self, path, on = 0 ):

		self.sprite = Sprite( path, 4 )

		self.scratch = Texture( "menu/scratch.png" )
		self.click = pygame.mixer.Sound( "menu/click.wav" )

		self.type = 0
		self.state = 0
		self.on = on
		self.mouseup = 0
Пример #42
0
class Skeleton(Character):

	def __init__(self, map_lvl, canvas, x, y):
		super().__init__()
		self.map_level = map_lvl
		self.texture = Texture(canvas, x, y)
		self.img = self.skeleton_img
		self.canvas = canvas
		self.position = {'x': x, 'y': y}

		self.hp = 2 * self.map_level * self.dice()
		self.dp = self.map_level/2 * self.dice()
		self.sp = self.map_level * self.dice()

	def draw(self):
		self.texture.draw_img(self.img)

	def __str__(self):
		return "(SKELETON) HP: {} | DP: {} | SP: {}".format(self.hp,
																							self.dp, self.sp)
Пример #43
0
	def __init__(self, map_lvl, canvas, x, y):
		super().__init__()
		self.map_level = map_lvl
		self.texture = Texture(canvas, x, y)
		self.img = self.skeleton_img
		self.canvas = canvas
		self.position = {'x': x, 'y': y}

		self.hp = 2 * self.map_level * self.dice()
		self.dp = self.map_level/2 * self.dice()
		self.sp = self.map_level * self.dice()
Пример #44
0
 def draw_scanline(self, va: Vertex, vb: Vertex, y: int, texture: Texture):
     x1 = int(va.position.x)
     x2 = int(vb.position.x)
     sign = 1 if x2 > x1 else -1
     factor = 0
     for x in range(x1, x2 + sign * 1, sign):
         if x1 != x2:
             factor = (x - x1) / (x2 - x1)
         # color = interpolate(v1.color, v2.color, factor)
         v = interpolate(va, vb, factor)
         color = texture.sample(v.u, v.v)
         self.draw_point(Vector(x, y), color)
Пример #45
0
def main():
    train_directory = '/home/mihai/Proiecte/AAM/Dataset/'
    shape_train_files = []
    texture_train_files = []

    for file_name in os.listdir(train_directory):
        if file_name.endswith(".pts"):
            file_name = os.path.splitext(file_name)[0]
            file_path = os.path.join(train_directory, file_name)
            shape_train_files.append(file_path + '.pts')
            texture_train_files.append(file_path + '.pgm')

    train_shapes = Shape()
    train_shapes.load(shape_train_files)

    aligned_shapes = train_shapes.align()
    mean_shape = Shape.mean(aligned_shapes)
    pca = train_shapes.pca(train_shapes.shapes)

    train_textures = Texture()
    train_textures.load(texture_train_files, train_shapes.shapes, mean_shape)
Пример #46
0
	def toCompiled(self, shader=None):

		if shader is None:
			shader = self.getShader()

		assert(shader)

		code = ""

		# items made up of 3 floats
		for what in ("diffuse_color","specular_color","ambient_color"):
			loc = shader.getUniformPos(what)
			if loc!=-1:
				code += "\tglUniform3fv(%s, 1, mat._%s)\n"%(loc,what)

		# items made up of 1 float
		for what in ("specular_exp","alpha"):
			loc = shader.getUniformPos(what)
			if loc!=-1:
				code += "\tglUniform1f(%s, mat._%s)\n"%(loc,what)

		# textures
		for i in xrange(3):
			loc = shader.getUniformPos("texture%s"%i)
			if loc!=-1:
				try: # see if the texture is already loaded
					self._texture[i].id()
				except:
					if self._texture[i] is None:
						self._texture[i] = Texture.getNullTexture()
					else:
						self._texture[i] = R.loadTexture(self._texture[i])

				code += "\tmat._texture[%s].bind(%s,%s)\n"%(i,i,loc)

		if not code:
			code = "def binder(): pass"
		else:
			code = "def binder():\n"+code


		c = compile(code, "<compiled material>", "exec")

		ns = dict(mat = self, glUniform3fv=glUniform3fv, glUniform1f=glUniform1f)
	
		exec c in ns

		return ns['binder']
Пример #47
0
	def __init__( self ):

		self.counter = 0
		self.quit = False

		#Textures
		self.preview = Text( "intro/Jaapokki-Regular.otf", 37 )
		self.shuriken = Texture( "intro/shuriken.png" )
		self.title = Text( "intro/Jaapokki-Regular.otf", 37 )
		self.author = Text( "intro/Jaapokki-Regular.otf", 37 )
		self.produced = Text( "intro/Jaapokki-Regular.otf", 37 )

		self.text_one = Text( "intro/Jaapokki-Regular.otf", 37 )
		self.text_two = Text( "intro/Jaapokki-Regular.otf", 37 )
		self.text_three = Text( "intro/Jaapokki-Regular.otf", 37 )
		self.text_four = Text( "intro/Jaapokki-Regular.otf", 37 )
Пример #48
0
 def __init__(self, ui, textureFile):
   super(SimpleScreen, self).__init__(ui)
   self._texture = Texture(textureFile)
Пример #49
0
class GlutWindow(WindowCallback):

    def __init__(self, screen_size: tuple, screen_pos: tuple=(0, 0),
                 game_mode: bool=False, title: str='Default Title', **params):
        width, height = screen_size
        self.screen_size = screen_size
        self.screen_pos = screen_pos
        self.width = width
        self.height = height
        self.z_near = 1.0
        self.z_far = 100.0
        self.fov = 60.0
        self.game_mode = game_mode
        self.title = title

        self._vbo = None
        self._vao = None
        self._ibo = None
        self._program = None
        self._texture = None
        self._vertices = None
        self._indexes = None
        self._camera = None
        self._pipeline = None
        self._scale = 0.0
        self._dir_light_color = 1.0, 1.0, 1.0
        self._dir_light_ambient_intensity = 0.5
        self._projection = ProjParams(
            self.width, self.height, self.z_near, self.z_far, self.fov)

        self._log = params.get("log", print)
        self._clear_color = params.get("clearcolor", (0, 0, 0, 0))
        self._vertex_attributes = {"Position": -1, "TexCoord": -1}

        self._init_glut()
        self._init_gl()
        self._create_vertex_buffer()
        self._create_index_buffer()

        self._effect = LightingTechnique("shaders/vs.glsl", "shaders/fs_lighting.glsl")
        self._effect.init()
        self._effect.enable()
        self._effect.set_texture_unit(0)

        self._texture = Texture(GL_TEXTURE_2D, "resources/test.png")
        if not self._texture.load():
            raise ValueError("cannot load texture")

    def _init_glut(self):
        """
        Basic GLUT initialization and callbacks binding
        """
        glutInit(sys.argv[1:])
        glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_3_2_CORE_PROFILE)
        glutInitWindowSize(self.width, self.height)
        if self.game_mode:
            glutGameModeString("{}x{}@32".format(self.width, self.height))
            glutEnterGameMode()
        else:
            glutCreateWindow(self.title.encode())
            glutInitWindowPosition(*self.screen_pos)
        # callbacks binding
        glutDisplayFunc(self.on_display)
        glutIdleFunc(self.on_display)
        glutPassiveMotionFunc(self.on_mouse)
        glutSpecialFunc(self.on_keyboard)

    def _init_gl(self):
        """
        OpenGL initialization
        """
        glEnable(GL_DEPTH_TEST)
        glDepthFunc(GL_LEQUAL)
        glClearColor(*self._clear_color)
        # seems strange because should be GL_BACK... maybe something with camera?
        glCullFace(GL_FRONT)
        glFrontFace(GL_CW)
        glEnable(GL_CULL_FACE)

    def _create_vertex_buffer(self):
        """
        Creates vertex array and vertex buffer and fills last one with data.
        """
        self._vertices = np.array([
            -1.0, -1.0, 0.5773, 0.0, 0.0,
            0.0, -1.0, -1.15475, 0.5, 0.0,
            1.0, -1.0, 0.5773, 1.0, 0.0,
            0.0, 1.0, 0.0, 0.5, 1.0
        ], dtype=np.float32)

        self._vao = glGenVertexArrays(1)
        glBindVertexArray(self._vao)
        self._vbo = glGenBuffers(1)
        glBindBuffer(GL_ARRAY_BUFFER, self._vbo)
        glBufferData(GL_ARRAY_BUFFER, self._vertices.nbytes, self._vertices, GL_STATIC_DRAW)

    def _create_index_buffer(self):
        """
        Creates index buffer.
        """
        self._indexes = np.array([
            0, 3, 1,
            1, 3, 2,
            2, 3, 0,
            0, 1, 2
        ], dtype=np.uint32)

        self._ibo = glGenBuffers(1)
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self._ibo)
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, self._indexes.nbytes, self._indexes, GL_STATIC_DRAW)

    @property
    def camera(self):
        return self._camera

    @camera.setter
    def camera(self, value):
        self._camera = value

    def on_display(self):
        """
        Rendering callback.
        """
        self._camera.render()

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        self._scale += 0.1
        pipeline = Pipeline(rotation=[0, self._scale, 0],
                            translation=[0, 0, 6],
                            projection=self._projection)
        pipeline.set_camera(self._camera)

        self._effect.set_wvp(pipeline.get_wvp())
        self._effect.set_directional_light(
            self._dir_light_color, self._dir_light_ambient_intensity)

        position, tex_coord = 0, 1
        glEnableVertexAttribArray(position)
        glEnableVertexAttribArray(tex_coord)

        glBindBuffer(GL_ARRAY_BUFFER, self._vbo)
        glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 20, ctypes.c_void_p(0))
        glVertexAttribPointer(tex_coord, 2, GL_FLOAT, GL_FALSE, 20, ctypes.c_void_p(12))
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self._ibo)

        self._texture.bind(GL_TEXTURE0)
        glDrawElements(GL_TRIANGLES, 18, GL_UNSIGNED_INT, ctypes.c_void_p(0))
        glDisableVertexAttribArray(position)
        glDisableVertexAttribArray(tex_coord)
        glutSwapBuffers()

    def on_mouse(self, x, y):
        """
        Mouse moving events handler.
        """
        self._camera.mouse(x, y)

    def on_keyboard(self, key, x, y):
        """
        Keyboard events handler.
        """
        if key == GLUT_KEY_F1:
            if not bool(glutLeaveMainLoop):
                sys.exit(0)
            glutLeaveMainLoop()
        if key == GLUT_KEY_PAGE_UP:
            self._dir_light_ambient_intensity += 0.05
        if key == GLUT_KEY_PAGE_DOWN:
            self._dir_light_ambient_intensity -= 0.05
        if self._camera:
            self._camera.keyboard(key)

    def run(self):
        glutMainLoop()
Пример #50
0
    def generateVideoButton(self):
        # for i in range(len(self.shapes)):
        #     print " "
        #     print self.shapes[i].name
        #     for j in range(len(self.shapes[i].faces)):
        #         print self.shapes[i].faces[j].faceOrientation, " : ", self.shapes[i].faces[j].facePoints
        
        mb = ModelBuilder()
        Models = []
        for i in self.shapes:
            each_model = mb.BuildModel(i)
            # Print out the 3D model's vertex and texel coordinate
            # print "Print out the 3D model's vertex and texel coordinate---------------------------"
            # for j in each_model:
            #     # j is one polygon
            #     print "Vertex is:"
            #     for k in j.Vertex:
            #         print k.x, k.y, k.z
            #     print "Texel is:"
            #     for n in j.Texel:
            #         print n.u, n.v
            Models.append(each_model)
        print "Models list size: ", len(Models)
        img = cv2.imread("project.png",cv2.CV_LOAD_IMAGE_COLOR)
        texture = Texture(img)
        points = []
        
        for i in range(0,len(Models),1):
            
            pointsOfEachModel = []
            if (i<5): # for single model building 4,11,12,13 and ground
                fileIndex = i
                for j in range(len(Models[i])): # j is surfaces of each model
                    pointsOfEachFace = texture.putTexture(Models[i][j])
                    pointsOfEachModel.extend(pointsOfEachFace)
                
            elif i==5: #5-6 compound building 10
                fileIndex = 5
                for j in range(5, 7):
                    for k in range(len(Models[j])): 
                        pointsOfEachFace = texture.putTexture(Models[j][k])
                        pointsOfEachModel.extend(pointsOfEachFace)

            elif i==7: #7-12 compound building 9
                fileIndex = 6
                for j in range(7, 13):
                    for k in range(len(Models[j])): 
                        pointsOfEachFace = texture.putTexture(Models[j][k])
                        pointsOfEachModel.extend(pointsOfEachFace)

            elif (i-13)>=0 and (i-13)%2==0: #compound buildings 1-8
                multiple = (i-13)/2
                fileIndex = 7 + multiple
                for j in range(i, i+2):
                    for k in range(len(Models[j])): 
                        pointsOfEachFace = texture.putTexture(Models[j][k])
                        pointsOfEachModel.extend(pointsOfEachFace)

            else:
                continue

            points = pointsOfEachModel
            fileRGB = open("Models/model_"+str(fileIndex)+".dat", "w+")
            for k in range(len(pointsOfEachModel)):
                point = "{0},{1},{2},{r},{g},{b}\n".format(points[k].x, points[k].y,points[k].z,r=points[k].r, g=points[k].g, b=points[k].b)
                fileRGB.write(point)
            print "Model "+str(fileIndex)+":"+str(k)+" points generated"

        print "----------UI Phase Finished----------"
        print "All models have been generated, please use main.py to generate fraems of video"
Пример #51
0
 def test_invalid_views(self):
     data = np.zeros((10, 10), dtype=np.uint8)
     T = Texture(data=data)
     Z = T[5:, 5:]
     T.resize((5, 5))
     assert Z._valid == False
Пример #52
0
 def test_resize_unresizeable(self):
     data = np.zeros((10, 10), dtype=np.uint8)
     T = Texture(data=data, resizeable=False)
     with self.assertRaises(RuntimeError):
         T.resize((5, 5))
Пример #53
0
 def test_resize_bad_shape(self):
     data = np.zeros((10, 10), dtype=np.uint8)
     T = Texture(data=data)
     with self.assertRaises(ValueError):
         T.resize((5, 5, 5))
Пример #54
0
 def test_set_oversized_data(self):
     data = np.zeros((10, 10), dtype=np.uint8)
     T = Texture(data=data)
     T.set_data(np.ones((20, 20)))
     assert T.shape == (20, 20)
     assert len(T._pending_data) == 1
Пример #55
0
 def test_set_misshaped_data(self):
     data = np.zeros(10, dtype=np.uint8)
     T = Texture(data=data)
     with self.assertRaises(ValueError):
         T.set_data(np.ones((10, 10)))
Пример #56
0
 def test_set_misplaced_data(self):
     data = np.zeros((10, 10), dtype=np.uint8)
     T = Texture(data=data)
     with self.assertRaises(ValueError):
         T.set_data(np.ones((5, 5)), offset=(8, 8))
Пример #57
0
def renderSkin(dst, vertsPerPrimitive, verts, index = None, objectMatrix = None,
               texture = None, UVs = None, textureMatrix = None,
               color = None, clearColor = None):

    if isinstance(dst, Texture):
        glBindTexture(GL_TEXTURE_2D, dst.textureId)
    elif isinstance(dst, Image):
        dst = Texture(image = dst)
    elif isinstance(dst, tuple):
        dimensions = dst
        dst = Texture(size = dimensions)
        if dst.width < dimensions[0] or dst.height < dimensions[1]:
            raise RuntimeError('Could not allocate render texture with dimensions: %s' % str(dst))
    else:
        raise RuntimeError('Unsupported destination: %r' % dst)

    width, height = dst.width, dst.height

    framebuffer = glGenFramebuffers(1)
    glBindFramebuffer(GL_FRAMEBUFFER, framebuffer)
    glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, dst.textureId, 0)
    glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, dst.textureId, 0)

    if clearColor is not None:
        glClearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3])
        glClear(GL_COLOR_BUFFER_BIT)

    glVertexPointer(verts.shape[-1], GL_FLOAT, 0, verts)

    if texture is not None and UVs is not None:
        if isinstance(texture, Image):
            tex = Texture()
            tex.loadImage(texture)
            texture = tex
        if isinstance(texture, Texture):
            texture = texture.textureId
        glEnable(GL_TEXTURE_2D)
        glEnableClientState(GL_TEXTURE_COORD_ARRAY)
        glBindTexture(GL_TEXTURE_2D, texture)
        glTexCoordPointer(UVs.shape[-1], GL_FLOAT, 0, UVs)

    if color is not None:
        glColorPointer(color.shape[-1], GL_UNSIGNED_BYTE, 0, color)
        glEnableClientState(GL_COLOR_ARRAY)
    else:
        glDisableClientState(GL_COLOR_ARRAY)
        glColor4f(1, 1, 1, 1)

    glDisableClientState(GL_NORMAL_ARRAY)
    glDisable(GL_LIGHTING)

    glDepthMask(GL_FALSE)
    glDisable(GL_DEPTH_TEST)
    # glDisable(GL_CULL_FACE)

    glPushAttrib(GL_VIEWPORT_BIT)
    glViewport(0, 0, width, height)

    glMatrixMode(GL_MODELVIEW)
    glPushMatrix()
    if objectMatrix is not None:
        glLoadTransposeMatrixd(objectMatrix)
    else:
        glLoadIdentity()

    glMatrixMode(GL_PROJECTION)
    glPushMatrix()
    glLoadIdentity()
    glOrtho(0, 1, 0, 1, -100, 100)

    if textureMatrix is not None:
        glMatrixMode(GL_TEXTURE)
        glPushMatrix()
        glLoadTransposeMatrixd(textureMatrix)

    if index is not None:
        glDrawElements(g_primitiveMap[vertsPerPrimitive-1], index.size, GL_UNSIGNED_INT, index)
    else:
        glDrawArrays(g_primitiveMap[vertsPerPrimitive-1], 0, verts[:,:,0].size)

    if textureMatrix is not None:
        glMatrixMode(GL_TEXTURE)
        glPopMatrix()

    glMatrixMode(GL_PROJECTION)
    glPopMatrix()

    glMatrixMode(GL_MODELVIEW)
    glPopMatrix()

    glPopAttrib()

    glEnable(GL_DEPTH_TEST)
    glDepthMask(GL_TRUE)

    glEnable(GL_LIGHTING)
    glEnableClientState(GL_NORMAL_ARRAY)

    glEnableClientState(GL_COLOR_ARRAY)

    glDisable(GL_TEXTURE_2D)
    glDisableClientState(GL_TEXTURE_COORD_ARRAY)

    surface = np.empty((height, width, 4), dtype = np.uint8)
    glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, surface)
    surface = Image(data = np.ascontiguousarray(surface[::-1,:,:3]))

    glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0)
    glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0)
    glBindFramebuffer(GL_FRAMEBUFFER, 0)
    glDeleteFramebuffers(np.array([framebuffer]))
    glBindTexture(GL_TEXTURE_2D, 0)

    return surface
Пример #58
0
    def sprite(self, filename):
        print " -- initializing point sprite {}".format(filename)

        self._sprite_texture = Texture.from_file(filename)
Пример #59
-46
   def sprite(self, filename):
      ''' Enable or disable point sprite rendering.
      
      If filename is not None a texture object will be created from the
      filename and point sprites will be used when rendering. If filename is
      None point sprite rendering will be disabled.

      filename -- path to point sprite texture (or None to disable sprites)
      '''

      if filename:
         #debug(msg='initializing point sprite').add('filename', filename).flush()
         self._sprite_texture = Texture.from_file(filename)
      else:
         #debug(msg='point sprite rendering disabled').flush()
         self._sprite_texture = None