PyOpenGL(or PyGame) pixel-sized textures - python

I downloaded a simple sample program for using textures with PyOpenGL, Python & PyGame, but when I tried to replace the original texture with this:
(If you don't see that, its a 2x2 pixels square, where all the pixels has different colors)
than it gave me THIS:
I DON'T WANT THIS UGLY WINDOW LOGO!!
The code I downloaded:
#!/usr/bin/env python
from OpenGL.GL import *
from OpenGL.GLU import *
import pygame
from pygame.locals import *
class Texture():
# simple texture class
# designed for 32 bit png images (with alpha channel)
def __init__(self,fileName):
self.texID=0
self.LoadTexture(fileName)
def LoadTexture(self,fileName):
try:
textureSurface = pygame.image.load(fileName)
textureData = pygame.image.tostring(textureSurface, "RGBA", 1)
self.texID=glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, self.texID)
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA,
textureSurface.get_width(), textureSurface.get_height(),
0, GL_RGBA, GL_UNSIGNED_BYTE, textureData )
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR)
except:
print "can't open the texture: %s"%(fileName)
def __del__(self):
glDeleteTextures(self.texID)
class Main():
def resize(self,(width, height)):
if height==0:
height=1
glViewport(0, 0, width, height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
#gluOrtho2D(-8.0, 8.0, -6.0, 6.0)
glFrustum(-2,2,-2,2,1,8)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
def init(self):
#set some basic OpenGL settings and control variables
glShadeModel(GL_SMOOTH)
glClearColor(0.0, 0.0, 0.0, 0.0)
glClearDepth(1.0)
glDisable(GL_DEPTH_TEST)
glDisable(GL_LIGHTING)
glDepthFunc(GL_LEQUAL)
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
#glEnable(GL_BLEND)
self.tutorial_texture=Texture("pixels.png")
self.demandedFps=30.0
self.done=False
self.x,self.y,self.z=0.0 , 0.0, -4.0
self.rX,self.rZ=0,0
def draw(self):
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
glDisable(GL_LIGHTING)
glEnable(GL_TEXTURE_2D)
#glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glPushMatrix()
glTranslatef(self.x, self.y, self.z)
glRotate(-self.rZ/3,0,0,1)
glRotate(-self.rX/3,1,0,0)
glColor4f(1.0, 1.0, 1.0,1.0)
glBindTexture(GL_TEXTURE_2D,self.tutorial_texture.texID)
glBegin(GL_QUADS)
glTexCoord2f(0.0,1.0)
glVertex3f(-1.0, 1.0,0.0)
glTexCoord2f(1.0,1.0)
glVertex3f(1.0, 1.0,-1.0)
glTexCoord2f(1.0,0.0)
glVertex3f(1.0, -1.0,0.0)
glTexCoord2f(0.0,0.0)
glVertex3f(-1.0, -1.0,1.0)
glEnd()
glBegin(GL_LINES)
glColor(1,17,0)
glVertex(0,0,0)
glVertex(3,0,0)
glColor(1,0,1)
glVertex(0,0,0)
glVertex(0,3,0)
glColor(0,1,1)
glVertex(0,0,0)
glVertex(0,0,3)
glEnd()
glPopMatrix()
def Input(self,fl):
#mpb=pygame.mouse.get_pressed() # mouse pressed buttons
kpb=pygame.key.get_pressed() # keyboard pressed buttons
msh=pygame.mouse.get_rel() # mouse shift
if kpb[K_ESCAPE] or kpb[K_q]:
self.done=True
if kpb[K_UP]:
self.y+=0.1
if kpb[K_DOWN]:
self.y-=0.1
if kpb[K_RIGHT]:
self.x+=0.1
if kpb[K_LEFT]:
self.x-=0.1
if fl: self.rZ-=msh[0]/3; self.rX-=msh[1]/3
def __init__(self):
glOrtho(0, 800, 0, 600, 0.0, 100.0)
video_flags = OPENGL|DOUBLEBUF|RESIZABLE
pygame.init()
pygame.display.set_mode((800,800), video_flags)
pygame.display.set_caption("www.jason.gd")
self.resize((800,800))
self.init()
fl=0
clock = pygame.time.Clock()
while 1:
for event in pygame.event.get():
if event.type == QUIT or self.done:
pygame.quit ()
break
if event.type==MOUSEBUTTONDOWN:
if event.button==4: self.z+=0.1
if event.button==5: self.z-=0.1
if event.button==2: fl=1
if event.type==MOUSEBUTTONUP:
if event.button==2: fl=0
if event.type==VIDEORESIZE: self.resize((event.w,event.h))
self.Input(fl)
self.draw()
pygame.display.flip()
#limit fps
clock.tick(self.demandedFps)
if __name__ == '__main__': Main()
When I tried to use bigger(512x512 px) textures, it worked fine.
How can I let the OpenGL to DO NOT mix the pixel borders? Or- the PyGame did this?

What you see here is the GL_LINEAR texture magnification mode (aka "bilinear filtering", which your code explicitely requests) in combination with the default GL_REPEAT texture coordinate repetition at the borders.
I'm not 100% sure which one of the two things you don't want.
You might try changing GL_LINEAR to GL_NEAREST:
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST)
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST)
and/or adding
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE)
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE)

Related

How can I "blit" my Pygame game onto an OpenGL surface?

I built my entire game around Pygame and want to put it on Steam. I learned at the end that I would need OpenGL support to be able to run Steam's Overlay. The code to initialize the display:
screen = pygame.display.set_mode((screen_width, screen_height), HWSURFACE | DOUBLEBUF | OPENGL)
Is there any way that I can create an OpenGL surface and blit my entire game onto that surface, so I can get OpenGL functionality (the Steam Overlay), without having to redo a lot of code and recreate a lot of the game? The game doesn't use a lot of resources, so I don't think there will be much of a lag (hopefully), so it's definitely a route I'd like to try.
Do I have any options here, aside from redoing the game in a different library?
Based on this question: Draw rectangle over texture OpenGL which discussed texture-mapping an OpenGL rectangle in PyGame ~
Here is some code which draws to an "off screen" PyGame surface. On each main-loop iteration, that surface is converted to an OpenGL texture map. This texture map is then mapped onto a rectangle which fills the screen.
The code is a fairly simple example, and perhaps you will need to optimise it a bit.
import pygame
import sys
from OpenGL.GL import *
from pygame.locals import *
# set pygame screen
pygame.init()
pygame.display.set_mode((500, 500), OPENGL | DOUBLEBUF)
pygame.display.init()
info = pygame.display.Info()
#colours
MIDNIGHT = ( 15, 0, 100 )
BUTTER = ( 255, 245, 100 )
# basic opengl configuration
glViewport(0, 0, info.current_w, info.current_h)
glDepthRange(0, 1)
glMatrixMode(GL_PROJECTION)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glShadeModel(GL_SMOOTH)
glClearColor(0.0, 0.0, 0.0, 0.0)
glClearDepth(1.0)
glDisable(GL_DEPTH_TEST)
glDisable(GL_LIGHTING)
glDepthFunc(GL_LEQUAL)
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
glEnable(GL_BLEND)
###
### Function to convert a PyGame Surface to an OpenGL Texture
### Maybe it's not necessary to perform each of these operations
### every time.
###
texID = glGenTextures(1)
def surfaceToTexture( pygame_surface ):
global texID
rgb_surface = pygame.image.tostring( pygame_surface, 'RGB')
glBindTexture(GL_TEXTURE_2D, texID)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP)
surface_rect = pygame_surface.get_rect()
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, surface_rect.width, surface_rect.height, 0, GL_RGB, GL_UNSIGNED_BYTE, rgb_surface)
glGenerateMipmap(GL_TEXTURE_2D)
glBindTexture(GL_TEXTURE_2D, 0)
# create pygame clock
clock = pygame.time.Clock()
# make an offscreen surface for drawing PyGame to
offscreen_surface = pygame.Surface((info.current_w, info.current_h))
text_font = pygame.font.Font( None, 30 ) # some default font
done = False
while not done:
# get quit event
for event in pygame.event.get():
if event.type == QUIT:
done = True
# Do all the PyGame operations to the offscreen surface
# So any backgrounds, sprites, etc. will get drawn to the offscreen
# rather than to the default window/screen.
offscreen_surface.fill( MIDNIGHT )
# write some nonsense to put something changing on the screen
words = text_font.render( "β-Moé-Moé count: "+str( pygame.time.get_ticks() ), True, BUTTER )
offscreen_surface.blit( words, (50, 250) )
# prepare to render the texture-mapped rectangle
glClear(GL_COLOR_BUFFER_BIT)
glLoadIdentity()
glDisable(GL_LIGHTING)
glEnable(GL_TEXTURE_2D)
#glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
#glClearColor(0, 0, 0, 1.0)
# draw texture openGL Texture
surfaceToTexture( offscreen_surface )
glBindTexture(GL_TEXTURE_2D, texID)
glBegin(GL_QUADS)
glTexCoord2f(0, 0); glVertex2f(-1, 1)
glTexCoord2f(0, 1); glVertex2f(-1, -1)
glTexCoord2f(1, 1); glVertex2f(1, -1)
glTexCoord2f(1, 0); glVertex2f(1, 1)
glEnd()
pygame.display.flip()
clock.tick(60)
pygame.quit()

Using PyOpenGL to display OpenCV image

I was looking for a basic python program which will display webcam feed using OpenCV and PyOpenGL. I did some searches, and came up with a code posted in stackoverflow
import cv2
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import numpy as np
import sys
#window dimensions
width = 1280
height = 720
nRange = 1.0
global capture
capture = None
def cv2array(im):
h,w,c=im.shape
a = np.fromstring(
im.tostring(),
dtype=im.dtype,
count=w*h*c)
a.shape = (h,w,c)
return a
def init():
#glclearcolor (r, g, b, alpha)
glClearColor(0.0, 0.0, 0.0, 1.0)
glutDisplayFunc(display)
glutReshapeFunc(reshape)
glutKeyboardFunc(keyboard)
glutIdleFunc(idle)
def idle():
#capture next frame
global capture
_,image = capture.read()
cv2.cvtColor(image,cv2.COLOR_BGR2RGB)
#you must convert the image to array for glTexImage2D to work
#maybe there is a faster way that I don't know about yet...
#print image_arr
# Create Texture
glTexImage2D(GL_TEXTURE_2D,
0,
GL_RGB,
720,1280,
0,
GL_RGB,
GL_UNSIGNED_BYTE,
image)
cv2.imshow('frame',image)
glutPostRedisplay()
def display():
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glEnable(GL_TEXTURE_2D)
#glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
#glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
#glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)
#this one is necessary with texture2d for some reason
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
# Set Projection Matrix
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluOrtho2D(0, width, 0, height)
# Switch to Model View Matrix
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
# Draw textured Quads
glBegin(GL_QUADS)
glTexCoord2f(0.0, 0.0)
glVertex2f(0.0, 0.0)
glTexCoord2f(1.0, 0.0)
glVertex2f(width, 0.0)
glTexCoord2f(1.0, 1.0)
glVertex2f(width, height)
glTexCoord2f(0.0, 1.0)
glVertex2f(0.0, height)
glEnd()
glFlush()
glutSwapBuffers()
def reshape(w, h):
if h == 0:
h = 1
glViewport(0, 0, w, h)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
# allows for reshaping the window without distoring shape
if w <= h:
glOrtho(-nRange, nRange, -nRange*h/w, nRange*h/w, -nRange, nRange)
else:
glOrtho(-nRange*w/h, nRange*w/h, -nRange, nRange, -nRange, nRange)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
def keyboard(key, x, y):
global anim
if key == chr(27):
sys.exit()
def main():
global capture
#start openCV capturefromCAM
capture = cv2.VideoCapture(0)
print capture
capture.set(3,1280)
capture.set(4,720)
glutInit(sys.argv)
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH)
glutInitWindowSize(width, height)
glutInitWindowPosition(100, 100)
glutCreateWindow("OpenGL + OpenCV")
init()
glutMainLoop()
main()
What i'm trying to do is to use OpenGL to display the camera-feed (in full screen) instead of cv2.imshow. I have a hope that it might be faster than imshow.
Can anyone please explain to me display, reshape and idle functions
also i cant run this code because it expects some argument which i still cant figure out.

Draw rectangle over texture OpenGL

I'm using python 3 with pygame and OpenGL to try to accomplish what I thought it would be a simple task: Drawing a rectangle.
The idea is to have a white rectangle over (or bellow) a transparent texture, but whenever I add the texture to the screen the rectangle vanishes, whether I render it before or after the texture.
Bellow is a sample code displaying the problem (you can add any Player1.png image of your choice, the problem will remain the same - at least in my computer)
import pygame
import sys
from OpenGL.GL import *
from pygame.locals import *
# set pygame screen
pygame.display.set_mode((500, 500), OPENGL | DOUBLEBUF)
info = pygame.display.Info()
# basic opengl configuration
glViewport(0, 0, info.current_w, info.current_h)
glDepthRange(0, 1)
glMatrixMode(GL_PROJECTION)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glShadeModel(GL_SMOOTH)
glClearColor(0.0, 0.0, 0.0, 0.0)
glClearDepth(1.0)
glDisable(GL_DEPTH_TEST)
glDisable(GL_LIGHTING)
glDepthFunc(GL_LEQUAL)
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
glEnable(GL_BLEND)
# load texture
surf = pygame.image.load('Player1.png')
s = pygame.image.tostring(surf, 'RGBA')
texID = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, texID)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 142, 65, 0, GL_RGBA, GL_UNSIGNED_BYTE, s)
glGenerateMipmap(GL_TEXTURE_2D)
glBindTexture(GL_TEXTURE_2D, 0)
# create pygame clock
MAINCLOCK = pygame.time.Clock()
# init screen
pygame.display.init()
while True:
# get quit event
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
# prepare to render screen
glClear(GL_COLOR_BUFFER_BIT)
glLoadIdentity()
glDisable(GL_LIGHTING)
glEnable(GL_TEXTURE_2D)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glClearColor(0, 0, 0, 1.0)
# draw texture
glBindTexture(GL_TEXTURE_2D, texID)
glBegin(GL_QUADS)
glTexCoord2f(0, 0); glVertex2f(-1, -1)
glTexCoord2f(0, 1); glVertex2f(-1, 1)
glTexCoord2f(1, 1); glVertex2f(1, 1)
glTexCoord2f(1, 0); glVertex2f(1, -1)
glEnd()
# draw rectangle
glColor3fv((1, 1, 1))
glRectf(-1, 1, 0, 0.5)
pygame.display.flip()
MAINCLOCK.tick(60)
It most likely has to do something on how OpenGL treats Textures vs Rects, but I'm not sure what.
BTW: I know the image is upside down
Thanks in advance
You have to enable two-dimensional texturing before you draw the texture, as you do it (glEnable(GL_TEXTURE_2D)).
But you have to disable two-dimensional texturing again, before you draw the rectangle:
# draw rectangle
glDisable(GL_TEXTURE_2D)
glColor3fv((1, 1, 1))
glRectf(-1, 1, 0, 0.5)
Note, the texture is still bound, when you draw the rectangle. Since you do not provide texture coordinates, when you draw the rectangle. This causes that the current texture coordinate is applied to the rectangle and a single texel is drawn all over the rectangle.
e.g. The last texture coordinate set was glTexCoord2f(1, 0):
Further note, if you would change the color for the rectangle, then the entire texture get tint by this color. If texturing is enabled, then by default the color of the texel is multiplied by the current color, because by default the texture environment mode (GL_TEXTURE_ENV_MODE) is GL_MODULATE. See glTexEnv.
glDisable(GL_TEXTURE_2D)
glColor3fv((1, 0, 0)) # red
glRectf(-1, 1, 0, 0.5)
Set the "white" color before you draw the texture:
glEnable(GL_TEXTURE_2D)
glColor3fv((1, 1, 1))

OpenGL - Show Texture Only

I'm working on a 2D isometric game, using pygame and pyopengl.
I'm drawing sprites as quads, with a texture. I managed to get the alpha transparency to work for the texture, but the quad itself is still filled in a solid color (whatever colour gl pipeline is set with at the time).
How do I hide the quad shape, and just show the texture?
Here is a pic showing the problem (gl pipeline set to pink/purple color):
The code is a bit messy, and I've been blindly copy 'n pasting gl calls hoping it solves the problem so there are bound to be quite a few calls in the wrong place or duplicated (or both).
GL Setup code (called once at start of script)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
glViewport(0, 0, screen_size[0], screen_size[1])
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0.0, screen_size[0], 0.0, screen_size[1], 0.0, 1.0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glDisable(GL_LIGHTING)
glEnable(GL_TEXTURE_2D)
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
Drawing setup code (called once at the start of each frame)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
glViewport(0, 0, screen_size[0], screen_size[1])
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0.0, screen_size[0], 0.0, screen_size[1], 0.0, 1.0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glDisable(GL_LIGHTING)
glEnable(GL_TEXTURE_2D)
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
Quad draw code (called for every sprite draw call):
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glEnable(GL_TEXTURE_2D)
glEnable(GL_ALPHA_TEST)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)
# Start new transformation matrix
glPushMatrix()
# Apply translation
glTranslatef(self.rect.centerx, self.rect.centery, 0.0)
# Start gl drawing cursor
glColor4f(1.0, 0.0, 1.0, 1.0)
# Bind the texture to this draw session
glBindTexture(GL_TEXTURE_2D, self.texture.id)
# Start drawing a quad
glBegin(GL_QUADS)
# Grab new copy of rect, and move to the origin
r = self.rect.copy()
r.center = (0, 0)
# Draw top left point
glTexCoord2f(1.0, 0.0)
glVertex2f(*r.topleft)
# Draw top right point
glTexCoord2f(0.0, 0.0)
glVertex2f(*r.topright)
# Draw bottom right point
glTexCoord2f(0.0, 1.0)
glVertex2f(*r.bottomright)
# Draw bottom left point
glTexCoord2f(1.0, 1.0)
glVertex2f(*r.bottomleft)
# End quad
glEnd()
# Apply transformation matrix
glPopMatrix()
The colored background behind your tiles is probably due to this line when you set up your texture:
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)
Just remove this as the default texture environment settings are probably fine for standard tile rendering. As an example of what messing with these parameters can do, if you wanted glColor calls to "tint" your texture instead, then replace GL_DECAL with GL_BLEND.
There is no need for any of those lighting calls included in your code as far as I can tell unless you are working with 3d models and ancient per-vertex lighting (I assume you are not since this is a 2d isometric game). Also you only need blending for this, no need for alpha testing. Assuming you are working with images with alpha (RGBA format), here is a simple demo that displays two tiles with a transparent background (supply your own image of course instead of ./images/grass.png):
import pygame
from pygame.locals import *
from OpenGL.GL import *
import sys
class Sprite(object):
def __init__(self):
self.x = 0
self.y = 0
self.width = 0
self.height = 0
self.texture = glGenTextures(1)
def load_texture(self, texture_url):
tex = pygame.image.load(texture_url)
tex_surface = pygame.image.tostring(tex, 'RGBA')
tex_width, tex_height = tex.get_size()
glBindTexture(GL_TEXTURE_2D, self.texture)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex_width, tex_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex_surface)
glBindTexture(GL_TEXTURE_2D, 0)
self.width = tex_width
self.height = tex_height
def set_position(self, x, y):
self.x = x
self.y = y
def render(self):
#glColor(1, 1, 1, 1)
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glBindTexture(GL_TEXTURE_2D, self.texture)
glBegin(GL_QUADS)
glTexCoord(0, 0)
glVertex(self.x, self.y, 0)
glTexCoord(0, 1)
glVertex(self.x, self.y + self.height, 0)
glTexCoord(1, 1)
glVertex(self.x + self.width, self.y + self.height, 0)
glTexCoord(1, 0)
glVertex(self.x + self.width, self.y, 0)
glEnd()
glBindTexture(GL_TEXTURE_2D, 0)
def init_gl():
window_size = width, height = (550, 400)
pygame.init()
pygame.display.set_mode(window_size, OPENGL | DOUBLEBUF)
glEnable(GL_TEXTURE_2D)
glMatrixMode(GL_PROJECTION)
glOrtho(0, width, height, 0, -1, 1)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
if __name__ == "__main__":
init_gl()
tile1 = Sprite()
tile1.load_texture("./images/grass.png")
tile1.set_position(50, 100)
tile2 = Sprite()
tile2.load_texture("./images/grass.png")
tile2.set_position(80, 130)
tiles = [tile1, tile2]
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
glClear(GL_COLOR_BUFFER_BIT)
glColor(1, 0, 0, 1)
for tile in tiles:
tile.render()
pygame.display.flip()
Let me know if this helps!
Well, either use blending, so that the alpha value actually has effect on opacity. Or use alpha testing, so that incoming fragments with an alpha below/above a certain threshold are discarded.
Blending requires to sort geometry back to front. And given what you want to do alpha testing may be the easier, more straightforward solution.
Update:
Either way it's imperative that the texture's alpha value makes it through to the fragment. If you were using shaders this would be as simple as making sure that the fragment output alpha would receive its value from the texture. But you're using the fixed function pipeline and the mess that's the texture environment state machine.
Using only a single texture your best bet would be a GL_REPLACE texture mode (completely ignores the vertex color). Or GL_MODULATE that takes the vertex color into account. Right now you're assumingly using GL_DECAL mode.
My suggestion: Drop the fixed function pipeline and use shaders. Much easier to get things related to texturing working. Also you'll hard pressed to find hardware that's not using shaders anyway (unless you're planning to run your program on stuff that's been built before 2004).

Pygame + OpenGL - how to draw text after glBegin()?

I found somewhere on StackOverflow this cross-platform way to draw text:
def drawText(x, y, text):
position = (x, y, 0)
font = pygame.font.Font(None, 64)
textSurface = font.render(text, True, (255,255,255,255),
(0,0,0,255))
textData = pygame.image.tostring(textSurface, "RGBA", True)
GL.glRasterPos3d(*position)
GL.glDrawPixels(textSurface.get_width(), textSurface.get_height(),
GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, textData)
The problem is that I cannot call drawText after I called glBegin(GL_QUADS). How can I create a rectangle and texture it with the text's contents, then display it so that this drawText could be called even after glBegin?
I found that I can't change the current texture inside of glBegin, so I had to redesign parts of my code. Here's an example of using pygame to create the texture, based on Python version of Nehe's tutorial, lesson 6:
#!/usr/bin/env python
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
import pygame
ESCAPE = '\033'
window = 0
texture = 0
A_TEX_NUMBER = None
B_TEX_NUMBER = None
def GenTextureForText(text):
font = pygame.font.Font(None, 64)
textSurface = font.render(text, True, (255,255,255,255),
(0,0,0,255))
ix, iy = textSurface.get_width(), textSurface.get_height()
image = pygame.image.tostring(textSurface, "RGBX", True)
glPixelStorei(GL_UNPACK_ALIGNMENT,1)
i = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, i)
glTexImage2D(GL_TEXTURE_2D, 0, 3, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, image)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)
return i
def InitGL(Width, Height):
global A_TEX_NUMBER, B_TEX_NUMBER
pygame.init()
A_TEX_NUMBER = GenTextureForText("a")
B_TEX_NUMBER = GenTextureForText("b")
glEnable(GL_TEXTURE_2D)
glClearColor(0.0, 0.0, 0.0, 0.0)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45.0, float(Width)/float(Height), 0.1, 100.0)
glMatrixMode(GL_MODELVIEW)
done = 1
def DrawGLScene():
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
glTranslatef(0.0,0.0,-10.0)
glBindTexture(GL_TEXTURE_2D, B_TEX_NUMBER)
glBegin(GL_QUADS)
glTexCoord2f(0.0, 0.0); glVertex3f(-1.0, -1.0, 1.0)
glTexCoord2f(1.0, 0.0); glVertex3f( 1.0, -1.0, 1.0)
glTexCoord2f(1.0, 1.0); glVertex3f( 1.0, 1.0, 1.0)
glTexCoord2f(0.0, 1.0); glVertex3f(-1.0, 1.0, 1.0)
glEnd()
glutSwapBuffers()
def keyPressed(*args):
if args[0] == ESCAPE:
glutDestroyWindow(window)
sys.exit()
def main():
global window
glutInit("")
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH)
glutInitWindowSize(640, 480)
glutInitWindowPosition(0, 0)
window = glutCreateWindow("Jeff Molofee's GL Code Tutorial ... NeHe '99")
glutDisplayFunc(DrawGLScene)
glutIdleFunc(DrawGLScene)
glutKeyboardFunc(keyPressed)
InitGL(640, 480)
glutMainLoop()
print "Hit ESC key to quit."
main()

Categories