Anonymous
Текстура изображения в Legacy OpenGL [закрыто]
Сообщение
Anonymous » 07 дек 2024, 18:18
Я пытаюсь самостоятельно изучить OpenGL, начиная с Legacy OpenGL 2.x, где шейдеры поддерживаются минимально, и пытаюсь понять, как работают графические процессоры и OpenGL. Моим основным источником обучения были несколько страниц StackOverflow и учебные пособия по PyOpenGL (да. Я использовал Python для своей работы).
В этом руководстве нет никакого способа получить текстуры. в модели OpenGL. Я изо всех сил стараюсь вручную научиться получать его с помощью ChatGPT или чего-то еще, но безуспешно.
Код ChatGPT:
Код: Выделить всё
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:
--------------------------------------------------------------------------- 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++ сейчас все будет работать).< /p>
Спасибо.
Подробнее здесь:
https://stackoverflow.com/questions/792 ... acy-opengl
1733584731
Anonymous
Я пытаюсь самостоятельно изучить OpenGL, начиная с Legacy OpenGL 2.x, где шейдеры поддерживаются минимально, и пытаюсь понять, как работают графические процессоры и OpenGL. Моим основным источником обучения были несколько страниц StackOverflow и учебные пособия по PyOpenGL (да. Я использовал Python для своей работы). В этом руководстве нет никакого способа получить текстуры. в модели OpenGL. Я изо всех сил стараюсь вручную научиться получать его с помощью ChatGPT или чего-то еще, но безуспешно. Код ChatGPT: [code]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() [/code] [code] Error: --------------------------------------------------------------------------- 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 [/code] Есть ли способ [b]просто визуализировать 3D-треугольник с фрагментом текстуры поверх него?[/b] (На Python или C++ сейчас все будет работать).< /p> Спасибо. Подробнее здесь: [url]https://stackoverflow.com/questions/79260660/image-texture-in-legacy-opengl[/url]