我正在尝试从 Legacy OpenGL 2.x 开始自学 OpenGL,其中对着色器的支持很少,并尝试了解 GPU 和 OpenGL 的工作原理。我的主要学习来源是一些 StackOverflow 页面和 PyOpenGL 教程(是的。我一直在使用 Python 来完成我的工作)。
本教程没有任何方法将纹理导入 OpenGL 模型。我正在尽力手动学习通过 ChatGPT 或其他有帮助的方法来获取它,但没有成功。
聊天GPT代码:
import pygame
from OpenGL.GL import *
from OpenGL.GL.shaders import compileProgram, compileShader
import numpy as np
# Vertex shader source
VERTEX_SHADER = """
#version 120
attribute vec3 position;
attribute vec2 texCoord;
varying vec2 fragTexCoord;
void main() {
fragTexCoord = texCoord;
gl_Position = vec4(position, 1.0);
}
"""
# Fragment shader source
FRAGMENT_SHADER = """
#version 120
varying vec2 fragTexCoord;
uniform sampler2D textureSampler;
void main() {
gl_FragColor = texture2D(textureSampler, fragTexCoord);
}
"""
def load_texture(image_path):
"""Load a texture from an image file."""
surface = pygame.image.load(image_path)
texture_data = pygame.image.tostring(surface, "RGB", 1)
width, height = surface.get_size()
texture = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, texture)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, texture_data)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
return texture
def main():
# Initialize pygame and OpenGL
pygame.init()
screen = pygame.display.set_mode((800, 600), pygame.OPENGL | pygame.DOUBLEBUF)
pygame.display.set_caption("Textured Triangle")
# Compile shaders and create shader program
shader = compileProgram(
compileShader(VERTEX_SHADER, GL_VERTEX_SHADER),
compileShader(FRAGMENT_SHADER, GL_FRAGMENT_SHADER),
)
glUseProgram(shader)
# Define triangle vertices and texture coordinates
vertices = np.array([
# Positions # Texture Coords
-0.5, -0.5, 0.0, 0.0, 0.0,
0.5, -0.5, 0.0, 1.0, 0.0,
0.0, 0.5, 0.0, 0.5, 1.0
], dtype=np.float32)
# Create and bind Vertex Buffer Object (VBO)
VBO = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, VBO)
glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW)
# Get attribute locations
position = glGetAttribLocation(shader, "position")
texCoord = glGetAttribLocation(shader, "texCoord")
# Enable position attribute
glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 5 * vertices.itemsize, ctypes.c_void_p(0))
glEnableVertexAttribArray(position)
# Enable texture coordinate attribute
glVertexAttribPointer(texCoord, 2, GL_FLOAT, GL_FALSE, 5 * vertices.itemsize, ctypes.c_void_p(3 * vertices.itemsize))
glEnableVertexAttribArray(texCoord)
# Load and bind texture
texture = load_texture("texture.jpg")
glUniform1i(glGetUniformLocation(shader, "textureSampler"), 0)
# Main loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
glClear(GL_COLOR_BUFFER_BIT)
# Draw the triangle
glBindTexture(GL_TEXTURE_2D, texture)
glDrawArrays(GL_TRIANGLES, 0, 3)
pygame.display.flip()
# Cleanup
glDeleteBuffers(1, [VBO])
glDeleteTextures([texture])
glDeleteProgram(shader)
pygame.quit()
if __name__ == "__main__":
main()
错误:
--------------------------------------------------------------------------- Error Traceback (most recent call last) Cell In[2], line 112 109 pygame.quit() 111 if __name__ == "__main__": --> 112 main() Cell In[2], line 79, in main() 76 texCoord = glGetAttribLocation(shader, "texCoord") 78 # Enable position attribute ---> 79 glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 5 * vertices.itemsize, ctypes.c_void_p(0)) 80 glEnableVertexAttribArray(position) 82 # Enable texture coordinate attribute File ~/programs/Nirvana/lib/python3.12/site-packages/OpenGL/latebind.py:63, in Curry.__call__(self, *args, **named) 61 def __call__( self, *args, **named ): 62 """returns self.wrapperFunction( self.baseFunction, *args, **named )""" ---> 63 return self.wrapperFunction( self.baseFunction, *args, **named ) File ~/programs/Nirvana/lib/python3.12/site-packages/OpenGL/GL/VERSION/GL_2_0.py:469, in glVertexAttribPointer(baseOperation, index, size, type, normalized, stride, pointer) 467 array = ArrayDatatype.asArray( pointer, type ) 468 key = ('vertex-attrib',index) --> 469 contextdata.setValue( key, array ) 470 return baseOperation( 471 index, size, type, 472 normalized, stride, 473 ArrayDatatype.voidDataPointer( array ) 474 ) File ~/programs/Nirvana/lib/python3.12/site-packages/OpenGL/contextdata.py:58, in setValue(constant, value, context, weak) 56 if getattr( value, '_no_cache_', False ): 57 return ---> 58 context = getContext( context ) 59 if weak: 60 storage = storedWeakPointers File ~/programs/Nirvana/lib/python3.12/site-packages/OpenGL/contextdata.py:40, in getContext(context) 38 if context == 0: 39 from OpenGL import error ---> 40 raise error.Error( 41 """Attempt to retrieve context when no valid context""" 42 ) 43 return context Error: Attempt to retrieve context when no valid context
有什么方法可以简单地渲染一个带有纹理片段的 3D 三角形吗?(在 Python 或 C++ 上,目前任何方法都可以)。
谢谢你。
Thuê Phòng Mảketing Dương Tùng Nâng Hiệu Quả – Tối Ưu Chi Phí?! Dương Tùng Marketing cung cấp dịch vụ thuê phòng marketing chuyên nghiệp, giúp doanh nghiệp tiết kiệm chi phí và tối ưu hóa hiệu quả. Với đội ngũ giàu kinh nghiệm、dịch vụ bao gồm nghiên cứu thị trường、lập chiến lược、quảng cáo (Facebook、Google)、SEO、quản lý不,电子邮件营销và thiết kế sáng tạo。 Quy trình hợp tác rõ ràng từ tư vấn đến triển khai và báo cáo。 Lợi ích nổi bật:tiếp cận khách hàng hiệu quả,tối ưu ngân sách và xây dựng thương hiệu bền vững。 Liên hệ Dương Tùng để tận dụng giải pháp marketing toàn diện! https://duongtungmarketing.info/video/thue-phong-marketing-duong-tung-nang-hieu-qua-toi-uu-chi-phi/