我正在尝试在 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()
我会尽量避免使用 pygame
使用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()