PyOpenGL正方形纹理

t5fffqht  于 2022-10-18  发布在  其他
关注(0)|答案(1)|浏览(259)

我正在尝试加载一个我的世界纹理在OpenGL中,有人能帮我吗?纹理:

我的代码:

import sys
from OpenGL.GLUT import *
from OpenGL.GL import *

def color(r, g, b):
    return (r/255, g/255, b/255)

def display():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glColor3f(*color(40, 101, 212))
    glBegin(GL_QUADS)
    glVertex3f(-0.5, -0.5, 0.0)
    glVertex3f(0.5, -0.5, 0.0)
    glVertex(0.5, 0.5, 0.0)
    glVertex(-0.5, 0.5, 0.0)
    glEnd()
    glFlush()

glutInit(sys.argv)
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)
glutInitWindowSize(400, 400)
glutCreateWindow("Square Test")
glutDisplayFunc(display)
glutMainLoop()

我会尽量避免使用假游戏

ltskdhd1

ltskdhd11#

使用Pillow加载镜像:

from PIL import Image
pil_image = Image.open('texture.jpg')

创建纹理对象:

pil_image = Image.open('d:/temp/texture.jpg')
texture_id = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, texture_id)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) 
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) 
format = GL_RGBA if pil_image.mode == 'RGBA' else GL_RGB
glTexImage2D(GL_TEXTURE_2D, 0, format, *pil_image.size, 0, format, GL_UNSIGNED_BYTE, pil_image.tobytes())

启用二维纹理:

glEnable(GL_TEXTURE_2D)

使用纹理坐标绘制几何图形:

glColor3f(1, 1, 1)
glBegin(GL_QUADS)
glTexCoord2f(0, 0)
glVertex3f(-0.5, -0.5, 0.0)
glTexCoord2f(1, 0)
glVertex3f(0.5, -0.5, 0.0)
glTexCoord2f(1, 1)
glVertex(0.5, 0.5, 0.0)
glTexCoord2f(0, 1)
glVertex(-0.5, 0.5, 0.0)
glEnd()

完整的示例:

import sys
from OpenGL.GLUT import *
from OpenGL.GL import *
from PIL import Image

def display():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glColor3f(1, 1, 1)
    glBegin(GL_QUADS)
    glTexCoord2f(0, 0)
    glVertex3f(-0.5, -0.5, 0.0)
    glTexCoord2f(1, 0)
    glVertex3f(0.5, -0.5, 0.0)
    glTexCoord2f(1, 1)
    glVertex(0.5, 0.5, 0.0)
    glTexCoord2f(0, 1)
    glVertex(-0.5, 0.5, 0.0)
    glEnd()
    glFlush()

glutInit(sys.argv)
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)
glutInitWindowSize(400, 400)
glutCreateWindow("Square Test")

pil_image = Image.open('texture.jpg')
texture_id = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, texture_id)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) 
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) 
format = GL_RGBA if pil_image.mode == 'RGBA' else GL_RGB
glTexImage2D(GL_TEXTURE_2D, 0, format, *pil_image.size, 0, format, GL_UNSIGNED_BYTE, pil_image.tobytes())

glEnable(GL_TEXTURE_2D)

glutDisplayFunc(display)
glutMainLoop()

相关问题