PyOpenGL not drawing anything after clearing - python

I used Glut for making window and wanted to draw triangle, then on click button redraw it, but after clearing window I can't draw again. Does something wrong with Buffer depth and buffer bit? If I cleared it do I need to setup both again in my draw function?
def drawSomething():
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
glTranslatef(-2.5, 0.5, -6.0)
glColor3f( 1.0, 1.5, 0.0 )
glPolygonMode(GL_FRONT, GL_FILL)
glBegin(GL_TRIANGLES)
glVertex3f(2.0,-1.2,0.0)
glVertex3f(2.6,0.0,0.0)
glVertex3f(2.9,-1.2,0.0)
glEnd()
glFlush()
def funcForUpdate():
glClearColor(0.0, 0.0, 0.0, 0)
glClear(GL_COLOR_BUFFER_BIT)
glEnable(GL_TEXTURE_2D)
glBegin(GL_QUADS)
glTexCoord2f(0.0, 0.0)
glVertex2f(0.0, 0.0)
glTexCoord2f(0.0, 1.0)
glVertex2f(0.0, width)
glTexCoord2f(1.0, 1.0)
glVertex2f(height, width)
glTexCoord2f(1.0, 0.0)
glVertex2f(height, 0.0)
glEnd()
glFlush()
def resizeUpdateFunc(width, height):
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
gluOrtho2D(0.0, width, 0.0, height)
def handleKey(bkey,x,y):
key = bkey.decode("utf-8")
if key == "a":
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
drawSomething()
glFlush()
glutInit()
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)
glutInitWindowSize(width, height)
glutInitWindowPosition(0, 0)
glutCreateWindow("test")
drawSomething()
glutDisplayFunc(funcForUpdate)
glutReshapeFunc(resizeUpdateFunc)
glutKeyboardFunc(handleKey)
glutMainLoop()

See glutDisplayFunc:
[...] sets the display callback for the current window. [...] The redisplay state for a window can be either set explicitly by calling glutPostRedisplay or implicitly as the result of window damage reported by the window system.
In fact, a triangle is drawn in drawSomething, but it is immediately overdrawn in funcForUpdate.
Add a state drawTriangle and set the state in handleKey:
drawTriangle = False
def handleKey(bkey, x, y):
global drawTriangle
key = bkey.decode("utf-8")
if key == "a":
drawTriangle = not drawTriangle
glutPostRedisplay()
Draw depending on the variable drawTriangle in funcForUpdate:
def funcForUpdate():
glClearColor(0, 0, 0, 0)
glClear(GL_COLOR_BUFFER_BIT)
# [...]
if drawTriangle:
# [...]
glFlush()
A complete example:
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
drawTriangle = False
def funcForUpdate():
glClearColor(0, 0, 0, 0)
glClear(GL_COLOR_BUFFER_BIT)
glColor3f(1, 1, 0)
glBegin(GL_QUADS)
glVertex2f(0.0, 0.0)
glVertex2f(0, height)
glVertex2f(width, height)
glVertex2f(width, 0)
glEnd()
if drawTriangle:
glPushMatrix()
glLoadIdentity()
glTranslate(width/2, height/2, 0)
glColor3f(1, 0, 0)
glBegin(GL_TRIANGLES)
glVertex3f(-width/4, -height/4, 0)
glVertex3f(width/4, -height/4, 0)
glVertex3f(width/4, height/4, 0)
glEnd()
glPopMatrix()
glFlush()
def resizeUpdateFunc(width, height):
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluOrtho2D(0.0, width, 0.0, height)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
def handleKey(bkey, x, y):
global drawTriangle
key = bkey.decode("utf-8")
if key == "a":
drawTriangle = not drawTriangle
glutPostRedisplay()
width, height = 320, 200
glutInit()
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)
glutInitWindowSize(width, height)
glutInitWindowPosition(0, 0)
glutCreateWindow("test")
glutDisplayFunc(funcForUpdate)
glutReshapeFunc(resizeUpdateFunc)
glutKeyboardFunc(handleKey)
glutMainLoop()

Related

Moving a point using cordinate in 2D OpenGL Python

Suppose I have a point in pixel (200,200), and I would like to just shift it to (400,400) pixel. Is there any way to do it without glClear() as I don't want my other objects to get erased?
Here is the code that I am using for drawing a single point:
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
def draw_points(x0,y0):
glPointSize(5)
glBegin(GL_POINTS)
glVertex2f(x0,y0)
glEnd()
def iterate():
glViewport(0, 0, 1000, 1000)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0.0, 1000, 0.0, 1000, 0.0, 1.0)
glMatrixMode (GL_MODELVIEW)
glLoadIdentity()
def showScreen():
elapesed_ms = glutGet(GLUT_ELAPSED_TIME)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
iterate()
glColor3f(255, 255, 255)
draw_points(200,200)
glutSwapBuffers()
glutInit()
glutInitDisplayMode(GLUT_RGBA)
glutInitWindowSize(1000, 1000)
glutInitWindowPosition(0, 0)
wind = glutCreateWindow(b"")
glutDisplayFunc(showScreen)
glutMainLoop()

OpenGl incomplete formation of the 3d cuboid when i use Gl_lines

from tokenize import Double
from OpenGL.GL import *
from OpenGL.GLU import *
import pygame
from pygame.locals import *
import serial
#ser = serial.Serial('/dev/tty.usbserial', 38400, timeout=1)
ser = serial.Serial('COM5', 38400, timeout=1)
ax = ay = az =0.0
dx = dy = dz =0.0
def resize(width, height):
if height==0:
height=1
glViewport(0, 0, width, height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45, 1.0*width/height, 0.1, 100.0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
def init():
glShadeModel(GL_SMOOTH)
glClearColor(0.0, 0.0, 0.0, 0.0)
glClearDepth(1.0)
glEnable(GL_DEPTH_TEST)
glDepthFunc(GL_LEQUAL)
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
def drawText(position, textString):
font = pygame.font.SysFont ("Courier", 18, True)
textSurface = font.render(textString, True, (255,255,255,255), (0,0,0,255))
textData = pygame.image.tostring(textSurface, "RGBA", True)
glRasterPos3d(*position)
glDrawPixels(textSurface.get_width(), textSurface.get_height(), GL_RGBA, GL_UNSIGNED_BYTE, textData)
def draw():
global rquad
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity()
glTranslatef(0,0.0,-7.0)
osd_text = "pitch: " + str("{0:.2f}".format(ay)) + ", roll: " + str("{0:.2f}".format(ax)) + ", yaw: " + str("{0:.2f}".format(az))
drawText((-2,-2, 2), osd_text)
drawText((-2,2, 0), "PRESS Z TO CALIBRATE OFFSETS")
# the way I'm holding the IMU board, X and Y axis are switched
# with respect to the OpenGL coordinate system
glRotatef((az-dz)*-1, 0.0, 1.0, 0.0) # Yaw, rotate around y-axis
glRotatef(ay-dy ,1.0,0.0,0.0) # Pitch, rotate around x-axis
glRotatef((-1*ax)-dx ,0.0,0.0,1.0) # Roll, rotate around z-axis
glBegin(GL_QUADS)
#glColor3f(0.0,1.0,0.0)
glVertex3f( 1.0, 0.2,-1.0)
glVertex3f(-1.0, 0.2,-1.0)
glVertex3f(-1.0, 0.2, 1.0)
glVertex3f( 1.0, 0.2, 1.0)
#glColor3f(1.0,0.5,0.0)
glVertex3f( 1.0,-0.2, 1.0)
glVertex3f(-1.0,-0.2, 1.0)
glVertex3f(-1.0,-0.2,-1.0)
glVertex3f( 1.0,-0.2,-1.0)
#glColor3f(1.0,0.0,0.0)
glVertex3f( 1.0, 0.2, 1.0)
glVertex3f(-1.0, 0.2, 1.0)
glVertex3f(-1.0,-0.2, 1.0)
glVertex3f( 1.0,-0.2, 1.0)
#glColor3f(1.0,1.0,0.0)
glVertex3f( 1.0,-0.2,-1.0)
glVertex3f(-1.0,-0.2,-1.0)
glVertex3f(-1.0, 0.2,-1.0)
glVertex3f( 1.0, 0.2,-1.0)
#glColor3f(0.0,0.0,1.0)
glVertex3f(-1.0, 0.2, 1.0)
glVertex3f(-1.0, 0.2,-1.0)
glVertex3f(-1.0,-0.2,-1.0)
glVertex3f(-1.0,-0.2, 1.0)
#glColor3f(1.0,0.0,1.0)
glVertex3f( 1.0, 0.2,-1.0)
glVertex3f( 1.0, 0.2, 1.0)
glVertex3f( 1.0,-0.2, 1.0)
glVertex3f( 1.0,-0.2,-1.0)
glEnd()
def read_data():
global ax, ay, az
ax = ay = az = 0
line = ser.readline().decode('utf-8')
line = line.strip()
imu = line.split(',')
ax = float(imu[0])
ay = float(imu[1])
az = float(imu[2])
def main():
video_flags = OPENGL|DOUBLEBUF
global dx, dy, dz
pygame.init()
screen = pygame.display.set_mode((640,480), video_flags)
pygame.display.set_caption("Press Esc to quit")
resize(640,480)
init()
frames = 0
ticks = pygame.time.get_ticks()
while 1:
event = pygame.event.poll()
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit() #* quit pygame properly
break
if event.type == KEYDOWN and event.key == K_z:
dx=ax
dy=ay
dz=az
read_data()
draw()
pygame.display.flip()
frames = frames+1
print ("fps: %d" % ((frames*1000)/(pygame.time.get_ticks()-ticks)))
ser.close()
if __name__ == '__main__': main()
I want to build an IMU visualization tool, this code works fine but as I am a complete beginner I am facing difficulties in building a custom model using GL_QUADS, even when i tried to display the cuboid(previously GL_Quads method) in GL_Lines there were a few portions missing as shown in the image, please guide me on how to build a model in OpenGL, I want to draw a 3D bi-copter in it.
Summary: please guide me on building any type of 3D polygon in OpenGL.
The vertex order of line primitives differs from the vertex order of quads. See GL_LINES not showing up on top of cube?. However, you can draw GL_QUADS and change the rasterization mode with glPolygonMode:
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
glBegin(GL_QUADS)
#[...]
glEnd()
Minimal example:
import pygame
from OpenGL.GL import *
from OpenGL.GLU import *
class Cube:
def __init__(self):
self.v = [(-1,-1,-1), ( 1,-1,-1), ( 1, 1,-1), (-1, 1,-1), (-1,-1, 1), ( 1,-1, 1), ( 1, 1, 1), (-1, 1, 1)]
self.surfaces = [(0,1,2,3), (5,4,7,6), (4,0,3,7),(1,5,6,2), (4,5,1,0), (3,2,6,7)]
def draw(self):
glEnable(GL_DEPTH_TEST)
glLineWidth(5)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
glBegin(GL_QUADS)
for i, quad in enumerate(self.surfaces):
for iv in quad:
glVertex3fv(self.v[iv])
glEnd()
glDisable( GL_POLYGON_OFFSET_FILL )
def set_projection(w, h):
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45, w / h, 0.1, 50.0)
glMatrixMode(GL_MODELVIEW)
pygame.init()
window = pygame.display.set_mode((400, 300), pygame.DOUBLEBUF | pygame.OPENGL | pygame.RESIZABLE)
clock = pygame.time.Clock()
set_projection(*window.get_size())
cube = Cube()
angle_x, angle_y = 0, 0
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.VIDEORESIZE:
glViewport(0, 0, event.w, event.h)
set_projection(event.w, event.h)
glLoadIdentity()
glTranslatef(0, 0, -5)
glRotatef(angle_y, 0, 1, 0)
glRotatef(angle_x, 1, 0, 0)
angle_x += 1
angle_y += 0.4
glClearColor(0.5, 0.5, 0.5, 1)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
cube.draw()
pygame.display.flip()
pygame.quit()
exit()

My pygame/pyopengl code seems to apply a texture to every surface

I'm throwing some code together to help me better understand python, pygame, pyopengl, and 3D rendering. I've used code from two different places and I'm integrating them by writing my own code as I go. I've textured cubes in one program and made camera movement work in another. But when I put them together, the colors are wrong and surfaces that I don't intend to texture are affected. I'm sure I'm missing something, but I can't figure it out.
Here is what the two programs look like seperately.
,
But when I put them together, I get this.
Here is my code, sorry I couldn't figure out how to attach it as a file!
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
import math
def tex_coord(x, y, n=4):
""" Return the bounding vertices of the texture square.
"""
m = 1.0 / n
dx = x * m
dy = y * m
return dx, dy, dx + m, dy, dx + m, dy + m, dx, dy + m
def tex_coords(top, bottom, side):
""" Return a list of the texture squares for the top, bottom and side.
"""
top = tex_coord(*top)
bottom = tex_coord(*bottom)
side = tex_coord(*side)
result = [
(top),
(bottom),
(side),
(side),
(side),
(side),
]
"""result = []
result.extend(top)
result.extend(bottom)
result.extend(side * 4)"""
return result
#block type names and location on template go here
BLOCK1 = tex_coords((3, 0), (3, 0), (3, 0))
def verts(x, y, z, n):
vertices = (
(1+(2*x), -1+(2*y), -1+(2*z)),
(1+(2*x), 1+(2*y), -1+(2*z)),
(-1+(2*x), 1+(2*y), -1+(2*z)),
(-1+(2*x), -1+(2*y), -1+(2*z)),
(1+(2*x), -1+(2*y), 1+(2*z)),
(1+(2*x), 1+(2*y), 1+(2*z)),
(-1+(2*x), -1+(2*y), 1+(2*z)),
(-1+(2*x), 1+(2*y), 1+(2*z))
)
return(vertices)
print(verts(0, 0, 0, 1))
edges = (
(0,1),
(0,3),
(0,4),
(2,1),
(2,3),
(2,7),
(6,3),
(6,4),
(6,7),
(5,1),
(5,4),
(5,7)
)
colors = (
(1,0,0),
(0,1,0),
(0,0,1),
(0,1,0),
(1,1,1),
(0,1,1),
(1,0,0),
(0,1,0),
(0,0,1),
(1,0,0),
(1,1,1),
(0,1,1),
)
surfaces = (
(0,1,2,3),
(3,2,7,6),
(6,7,5,4),
(4,5,1,0),
(1,5,7,2),
(4,0,3,6)
)
forced = False
def Cube(vx,vy,vz,block):
if not forced:
glBegin(GL_QUADS)
y = 0
for surface in surfaces:
x = 0
y+=1
for vertex in surface:
x+=1
#glColor3fv(colors[x])
glTexCoord2f(block[y-1][2*(x-1)], block[y-1][(2*x)-1])
#print(block[y-1][2*(x-1)], block[y-1][(2*x)-1])
glVertex3fv(verts(vx,vy,vz,1)[vertex])
glEnd()
glBegin(GL_LINES)
for edge in edges:
for vertex in edge:
glVertex3fv(verts(vx,vy,vz,1)[vertex])
glEnd()
else:
texX = 0.75
texY = 0.25
glBegin(GL_QUADS)
glTexCoord2f(0.0+texX, 0.0)
glVertex3f(-1.0, -1.0, 1.0)
glTexCoord2f(0.25+texX, 0.0)
glVertex3f(1.0, -1.0, 1.0)
glTexCoord2f(0.25+texX, 0.25)
glVertex3f(1.0, 1.0, 1.0)
glTexCoord2f(0.0+texX, 0.25)
glVertex3f(-1.0, 1.0, 1.0)
glEnd()
def loadTexture():
textureSurface = pygame.image.load('texture2.png')
textureData = pygame.image.tostring(textureSurface, "RGBA", 1)
width = textureSurface.get_width()
height = textureSurface.get_height()
glEnable(GL_TEXTURE_2D)
texid = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, texid)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height,
0, GL_RGBA, GL_UNSIGNED_BYTE, textureData)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
return texid
pygame.init()
display = (800, 600)
scree = pygame.display.set_mode(display, DOUBLEBUF | OPENGL)
glEnable(GL_DEPTH_TEST)
glEnable(GL_LIGHTING)
glShadeModel(GL_SMOOTH)
glEnable(GL_COLOR_MATERIAL)
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE)
glEnable(GL_LIGHT0)
glLightfv(GL_LIGHT0, GL_AMBIENT, [0.5, 0.5, 0.5, 1])
glLightfv(GL_LIGHT0, GL_DIFFUSE, [1.0, 1.0, 1.0, 1])
"""
glClearColor(0.0, 0.0, 0.0, 0.0)
glClearDepth(1.0)
glDepthMask(GL_TRUE)
glDepthFunc(GL_LESS)
glEnable(GL_DEPTH_TEST)
#glEnable(GL_CULL_FACE)
#glCullFace(GL_FRONT)
##glFrontFace(GL_CCW)
##glShadeModel(GL_SMOOTH)
glDepthRange(0.0,1.0)
"""
sphere = gluNewQuadric()
glMatrixMode(GL_PROJECTION)
gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)
glMatrixMode(GL_MODELVIEW)
gluLookAt(0, -8, 0, 0, 0, 0, 0, 0, 1)
viewMatrix = glGetFloatv(GL_MODELVIEW_MATRIX)
glLoadIdentity()
# init mouse movement and center mouse on screen
displayCenter = [scree.get_size()[i] // 2 for i in range(2)]
mouseMove = [0, 0]
pygame.mouse.set_pos(displayCenter)
loadTexture()
up_down_angle = 0.0
paused = False
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE or event.key == pygame.K_RETURN:
run = False
if event.key == pygame.K_PAUSE or event.key == pygame.K_p:
paused = not paused
pygame.mouse.set_pos(displayCenter)
if not paused:
if event.type == pygame.MOUSEMOTION:
mouseMove = [event.pos[i] - displayCenter[i] for i in range(2)]
pygame.mouse.set_pos(displayCenter)
if not paused:
# get keys
keypress = pygame.key.get_pressed()
#mouseMove = pygame.mouse.get_rel()
# init model view matrix
glLoadIdentity()
# apply the look up and down
up_down_angle += mouseMove[1]*0.1
glRotatef(up_down_angle, 1.0, 0.0, 0.0)
# init the view matrix
glPushMatrix()
glLoadIdentity()
# apply the movment
if keypress[pygame.K_w]:
glTranslatef(0,0,0.1)
if keypress[pygame.K_s]:
glTranslatef(0,0,-0.1)
if keypress[pygame.K_d]:
glTranslatef(-0.1,0,0)
if keypress[pygame.K_a]:
glTranslatef(0.1,0,0)
if keypress[pygame.K_LSHIFT]:
glTranslatef(0,0.5,0)
if keypress[pygame.K_SPACE]:
glTranslatef(0,-0.5,0)
# apply the left and right rotation
glRotatef(mouseMove[0]*0.1, 0.0, 1.0, 0.0)
# multiply the current matrix by the get the new view matrix and store the final vie matrix
glMultMatrixf(viewMatrix)
viewMatrix = glGetFloatv(GL_MODELVIEW_MATRIX)
# apply view matrix
glPopMatrix()
glMultMatrixf(viewMatrix)
#glLightfv(GL_LIGHT0, GL_POSITION, [1, -1, 1, 0])
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
glPushMatrix()
Cube(0,0,0,BLOCK1)
Cube(1,0,0,BLOCK1)
Cube(0,1,0,BLOCK1)
Cube(0,0,1,BLOCK1)
Cube(-2,0,0,BLOCK1)
glColor4f(0.5, 0.5, 0.5, 1)
glBegin(GL_QUADS)
glVertex3f(-10, -10, -2)
glVertex3f(10, -10, -2)
glVertex3f(10, 10, -2)
glVertex3f(-10, 10, -2)
glEnd()
glTranslatef(-1.5, 0, 0)
glColor4f(0.5, 0.2, 0.2, 1)
gluSphere(sphere, 1.0, 32, 16)
glTranslatef(3, 0, 0)
glColor4f(0.2, 0.2, 0.5, 1)
gluSphere(sphere, 1.0, 32, 16)
glPopMatrix()
pygame.display.flip()
pygame.time.wait(10)
pygame.quit()
I'd be very thankful if someone could explain this to me!
Edit: Thank you Rabbid76!!!
Here is a picture, and my working code.
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
import math
def tex_coord(x, y, n=4):
""" Return the bounding vertices of the texture square.
"""
m = 1.0 / n
dx = x * m
dy = y * m
return dx, dy, dx + m, dy, dx + m, dy + m, dx, dy + m
def tex_coords(top, bottom, side):
""" Return a list of the texture squares for the top, bottom and side.
"""
top = tex_coord(*top)
bottom = tex_coord(*bottom)
side = tex_coord(*side)
result = [
(top),
(bottom),
(side),
(side),
(side),
(side),
]
"""result = []
result.extend(top)
result.extend(bottom)
result.extend(side * 4)"""
return result
#block type names and location on template go here
BLOCK1 = tex_coords((3, 0), (3, 0), (3, 0))
def verts(x, y, z, n):
vertices = (
(1+(2*x), -1+(2*y), -1+(2*z)),
(1+(2*x), 1+(2*y), -1+(2*z)),
(-1+(2*x), 1+(2*y), -1+(2*z)),
(-1+(2*x), -1+(2*y), -1+(2*z)),
(1+(2*x), -1+(2*y), 1+(2*z)),
(1+(2*x), 1+(2*y), 1+(2*z)),
(-1+(2*x), -1+(2*y), 1+(2*z)),
(-1+(2*x), 1+(2*y), 1+(2*z))
)
return(vertices)
print(verts(0, 0, 0, 1))
edges = (
(0,1),
(0,3),
(0,4),
(2,1),
(2,3),
(2,7),
(6,3),
(6,4),
(6,7),
(5,1),
(5,4),
(5,7)
)
colors = (
(1,0,0),
(0,1,0),
(0,0,1),
(0,1,0),
(1,1,1),
(0,1,1),
(1,0,0),
(0,1,0),
(0,0,1),
(1,0,0),
(1,1,1),
(0,1,1),
)
surfaces = (
(0,1,2,3),
(3,2,7,6),
(6,7,5,4),
(4,5,1,0),
(1,5,7,2),
(4,0,3,6)
)
forced = False
def Cube(vx,vy,vz,block):
if not forced:
glBegin(GL_QUADS)
y = 0
for surface in surfaces:
x = 0
y+=1
for vertex in surface:
x+=1
#glColor3fv(colors[x])
glTexCoord2f(block[y-1][2*(x-1)], block[y-1][(2*x)-1])
#print(block[y-1][2*(x-1)], block[y-1][(2*x)-1])
glVertex3fv(verts(vx,vy,vz,1)[vertex])
glEnd()
glBegin(GL_LINES)
for edge in edges:
for vertex in edge:
glVertex3fv(verts(vx,vy,vz,1)[vertex])
glEnd()
else:
texX = 0.75
texY = 0.25
glBegin(GL_QUADS)
glTexCoord2f(0.0+texX, 0.0)
glVertex3f(-1.0, -1.0, 1.0)
glTexCoord2f(0.25+texX, 0.0)
glVertex3f(1.0, -1.0, 1.0)
glTexCoord2f(0.25+texX, 0.25)
glVertex3f(1.0, 1.0, 1.0)
glTexCoord2f(0.0+texX, 0.25)
glVertex3f(-1.0, 1.0, 1.0)
glEnd()
def loadTexture():
textureSurface = pygame.image.load('texture2.png')
textureData = pygame.image.tostring(textureSurface, "RGBA", 1)
width = textureSurface.get_width()
height = textureSurface.get_height()
glColor3f(0.5, 0.5, 0.5)
glEnable(GL_TEXTURE_2D)
texid = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, texid)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height,
0, GL_RGBA, GL_UNSIGNED_BYTE, textureData)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
return texid
glDisable(GL_TEXTURE_2D)
pygame.init()
display = (800, 600)
scree = pygame.display.set_mode(display, DOUBLEBUF | OPENGL)
glEnable(GL_DEPTH_TEST)
glEnable(GL_LIGHTING)
glShadeModel(GL_SMOOTH)
glEnable(GL_COLOR_MATERIAL)
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE)
glEnable(GL_LIGHT0)
glLightfv(GL_LIGHT0, GL_AMBIENT, [0.5, 0.5, 0.5, 1])
glLightfv(GL_LIGHT0, GL_DIFFUSE, [1.0, 1.0, 1.0, 1])
"""
glClearColor(0.0, 0.0, 0.0, 0.0)
glClearDepth(1.0)
glDepthMask(GL_TRUE)
glDepthFunc(GL_LESS)
glEnable(GL_DEPTH_TEST)
#glEnable(GL_CULL_FACE)
#glCullFace(GL_FRONT)
##glFrontFace(GL_CCW)
##glShadeModel(GL_SMOOTH)
glDepthRange(0.0,1.0)
"""
sphere = gluNewQuadric()
glMatrixMode(GL_PROJECTION)
gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)
glMatrixMode(GL_MODELVIEW)
gluLookAt(0, -8, 0, 0, 0, 0, 0, 0, 1)
viewMatrix = glGetFloatv(GL_MODELVIEW_MATRIX)
glLoadIdentity()
# init mouse movement and center mouse on screen
displayCenter = [scree.get_size()[i] // 2 for i in range(2)]
mouseMove = [0, 0]
pygame.mouse.set_pos(displayCenter)
loadTexture()
up_down_angle = 0.0
paused = False
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE or event.key == pygame.K_RETURN:
run = False
if event.key == pygame.K_PAUSE or event.key == pygame.K_p:
paused = not paused
pygame.mouse.set_pos(displayCenter)
if not paused:
if event.type == pygame.MOUSEMOTION:
mouseMove = [event.pos[i] - displayCenter[i] for i in range(2)]
pygame.mouse.set_pos(displayCenter)
if not paused:
# get keys
keypress = pygame.key.get_pressed()
#mouseMove = pygame.mouse.get_rel()
# init model view matrix
glLoadIdentity()
# apply the look up and down
up_down_angle += mouseMove[1]*0.1
glRotatef(up_down_angle, 1.0, 0.0, 0.0)
# init the view matrix
glPushMatrix()
glLoadIdentity()
# apply the movment
if keypress[pygame.K_w]:
glTranslatef(0,0,0.1)
if keypress[pygame.K_s]:
glTranslatef(0,0,-0.1)
if keypress[pygame.K_d]:
glTranslatef(-0.1,0,0)
if keypress[pygame.K_a]:
glTranslatef(0.1,0,0)
if keypress[pygame.K_LSHIFT]:
glTranslatef(0,0.5,0)
if keypress[pygame.K_SPACE]:
glTranslatef(0,-0.5,0)
# apply the left and right rotation
glRotatef(mouseMove[0]*0.1, 0.0, 1.0, 0.0)
# multiply the current matrix by the get the new view matrix and store the final vie matrix
glMultMatrixf(viewMatrix)
viewMatrix = glGetFloatv(GL_MODELVIEW_MATRIX)
# apply view matrix
glPopMatrix()
glMultMatrixf(viewMatrix)
#glLightfv(GL_LIGHT0, GL_POSITION, [1, -1, 1, 0])
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
glPushMatrix()
glEnable(GL_TEXTURE_2D)
Cube(0,0,0,BLOCK1)
Cube(1,0,0,BLOCK1)
Cube(0,1,0,BLOCK1)
Cube(0,0,1,BLOCK1)
Cube(-2,0,0,BLOCK1)
glDisable(GL_TEXTURE_2D)
glColor4f(0.5, 0.5, 0.5, 1)
glBegin(GL_QUADS)
glVertex3f(-10, -10, -2)
glVertex3f(10, -10, -2)
glVertex3f(10, 10, -2)
glVertex3f(-10, 10, -2)
glEnd()
glTranslatef(-1.5, 0, 0)
glColor4f(0.5, 0.2, 0.2, 1)
gluSphere(sphere, 1.0, 32, 16)
glTranslatef(3, 0, 0)
glColor4f(0.2, 0.2, 0.5, 1)
gluSphere(sphere, 1.0, 32, 16)
glColor3f(1, 1, 1)
glPopMatrix()
pygame.display.flip()
pygame.time.wait(10)
pygame.quit()
OpenGL is a state engine. A state is kept until it is changed again. Two-dimensional texturing can be enabled and disabled, see glEnable.
When texturing is activated, by default the color of the pixel is multiplied by the current color, because by default the texture environment mode (GL_TEXTURE_ENV_MODE) is GL_MODULATE. See glTexEnv.
This causes that the color of the piles of the texture is "mixed" by the last color which you have set by glColor4f.
Set a "white" color and enable texturing before you render an object with a texture. Disable texturing before you draw an object with colors:
glColor3f(1.0f, 1.0f, 1.0f)
glEnable(GL_TEXTURE_2D)
# draw object with texture
# [...]
glDisable(GL_TEXTURE_2D)
# draw object with color
# [...]
Changes in your code:
forced = False
def Cube(vx,vy,vz,block):
glColor4f(1, 1, 1, 1) # <--
glEnable(GL_TEXTURE_2D)
if not forced:
glBegin(GL_QUADS)
for y, surface in enumerate(surfaces):
for x, vertex in enumerate(surface):
glTexCoord2f(block[y-1][2*(x-1)], block[y-1][(2*x)-1])
glVertex3fv(verts(vx,vy,vz,1)[vertex])
glEnd()
glDisable(GL_TEXTURE_2D) # <--
glColor4f(0, 0, 0, 1)
glBegin(GL_LINES)
for edge in edges:
for vertex in edge:
glVertex3fv(verts(vx,vy,vz,1)[vertex])
glEnd()
# [...]
run = True
while run:
# [...]
Cube(0,0,0,BLOCK1)
Cube(1,0,0,BLOCK1)
Cube(0,1,0,BLOCK1)
Cube(0,0,1,BLOCK1)
Cube(-2,0,0,BLOCK1)
glDisable(GL_TEXTURE_2D) # <--
glColor4f(0.5, 0.5, 0.5, 1)
glBegin(GL_QUADS)
glVertex3f(-10, -10, -2)
glVertex3f(10, -10, -2)
glVertex3f(10, 10, -2)
glVertex3f(-10, 10, -2)
glEnd()
# [...]

OpenCV Python OpenGL Texture

I want to overlay 3d objects on OpenCV feed. I found an example here That uses webcam video as texture in OpenGL. I changed some part so that it works with cv2. Now the output is something strange
CODE
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()
I find it very unlikely that your camera is providing a 720 pixel wide and 1280 pixel high image as you tell to OpenGL here:
glTexImage2D(GL_TEXTURE_2D,
0,
GL_RGB,
720,1280, // <---- HERE
0,
GL_RGB,
GL_UNSIGNED_BYTE,
image)
It seems you just mixed up those two parametes, so the data is reinterpreted as such, resulting in the output you got.

Python OpenGL module - can't render basic triangle

I'm trying to use the OpenGL module with Python.
Here is my source:
pygame.init()
screen = pygame.display.set_mode((800, 600), HWSURFACE|OPENGL|DOUBLEBUF)
def init():
glEnable(GL_DEPTH_TEST)
glShadeModel(GL_FLAT)
glClearColor(1.0, 1.0, 1.0, 0.0)
glEnable(GL_COLOR_MATERIAL)
glEnable(GL_LIGHTING)
glEnable(GL_LIGHT0)
glLight(GL_LIGHT0, GL_POSITION, (0, 1, 1, 0))
def draw():
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
glColor3fv((25, 123, 180))
glBegin(GL_TRIANGLES)
glVertex3f( 0.0, 10.0, 0.0)
glVertex3f(-10.0,-10.0, 0.0)
glVertex3f( 10.0,-10.0, 0.0)
glEnd()
def run():
init()
while True:
draw()
pygame.display.flip()
run()
Can anyone see what is wrong? I'm just trying to draw a simple 3 pointed vertex, yet nothing shows up on the screen. Occasionally I get a bright pink screen. I'm confident it's a basic error.
You need to setup view and projection matrices.
http://www.opengl.org/resources/faq/technical/transformations.htm#tran0090

Categories

Resources