简体   繁体   中英

PyOpenGL numpy texture appears as solid color

I'm trying to set numpy arrays as OpenGl textures in pygame. The problem is that only the first pixel is taken as texture data and instead of a random pattern (for example) I only get a random color every time.

import pygame
from pygame.locals import *

from OpenGL.GL import *
from OpenGL.GLU import *

import numpy as np

#Settings
width = 200
height = 300
resolution = (800,600)
texture_data = np.random.randint(256,size=(height, width, 3))

#pygame init
pygame.init()
gameDisplay = pygame.display.set_mode(resolution,OPENGL)

#OpenGL init
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0,resolution[0],0,resolution[1],-1,1)
glMatrixMode(GL_MODELVIEW)
glDisable(GL_DEPTH_TEST)
glClearColor(0.0,0.0,0.0,0.0)
glEnable(GL_TEXTURE_2D)

#Set texture
texture = glGenTextures(1)
glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
glBindTexture(GL_TEXTURE_2D, texture)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, texture_data)
glGenerateMipmap(GL_TEXTURE_2D)

glActiveTexture(GL_TEXTURE0)

#Clean start
glClear(GL_COLOR_BUFFER_BIT)
glLoadIdentity()

#draw rectangle
glTranslatef(300,200,0)
glBegin(GL_QUADS)
glVertex2f(0,0)
glVertex2f(0,height)
glVertex2f(width,height)
glVertex2f(width,0)
glEnd()
glFlush()

#game loop until exit
gameExit = False
while not gameExit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameExit = True

    #throttle
    pygame.time.wait(100)

As pointed out by genpfault I was missing texture coordinates. I needed to add them to the rectangle drawing part.

#draw rectangle
glTranslatef(300,200,0)
glBegin(GL_QUADS)

glTexCoord(0,0)
glVertex2f(0,0)

glTexCoord(0,1)
glVertex2f(0,height)

glTexCoord(1,1)
glVertex2f(width,height)

glTexCoord(1,0)
glVertex2f(width,0)

glEnd()
glFlush()

Read this if you are lost on how texture mapping works:

OpenGL Programming Guide - Chapter 9 Texture Mapping

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM