I tried to use the glReadPixels method to color code a simple triangle in the screen, just without any secondary render functions, etc. but it didn't give the good result. Code:
import pygame as pg
from OpenGL.GL import *
pg.display.set_mode((500,500),pg.OPENGL)
glClearColor(0.5,0.0,0.5,0.0)
done=0
def first():
glColor3f(0.5,0.6,0.7)
glBegin(GL_TRIANGLES)
glVertex(0.0,0.0,0.0)
glVertex(1.0,0.0,0.0)
glVertex(0.0,1.0,0.0)
glEnd()
cl=0
clock=pg.time.Clock()
while not done:
for event in pg.event.get():
if event.type==pg.QUIT: done=1
elif event.type==pg.MOUSEBUTTONDOWN:
pos=pg.mouse.get_pos()
color=glReadPixels(pos[0],pos[1],1,1,GL_RGB,GL_FLOAT)
print color, pos[0], pos[1])
glClear(GL_COLOR_BUFFER_BIT)
first()
pg.display.flip()
clock.tick(20)
pg.quit()
But it always gives the SAME color output: [[[ 0.50196081 0. 0.50196081]]] 288 217 How can I fix it?
Your main problem is that glReadPixels accepts bottom-left origin and pygame gives top-left.
First, you should always save your pygame Surface
(for the reason I will soon demonstrate). So:
window = pg.display.set_mode((500,500),pg.OPENGL)
Now you can access window.width
and window.height
. So now your glReadPixels
will get the proper place:
color=glReadPixels(x,window.height-y,1,1,GL_RGB,GL_FLOAT)
PS: If you do want the most recent color, you should just put your colour detection after first()
but before pg.display.flip()
(OpenGL is always bound to the back buffer (unless you were to specify otherwise (but you wouldn't want to)))
EDIT: pg, not py
EDIT: I was wrong, it's in pixels. My bad.