[Python] Image texture in Legacy OpenGL [closed]

Discussão em 'Python' iniciado por Stack, Dezembro 7, 2024.

  1. Stack

    Stack Membro Participativo

    I'm trying to self-learn OpenGL starting from Legacy OpenGL 2.x where there's minimal support for shaders and trying to understand how GPUs and OpenGL works. My primary source of learning had been a few StackOverflow pages and PyOpenGL tutorials (Yes. I've been using Python for my job).

    The tutorial doesn't have any way to get textures into OpenGL Models. I'm trying my best to manually learn to get it by ChatGPT or something that helps without any success.

    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()




    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


    Is there any way to simply render a 3D Triangle with a texture fragment over it? (On Python or C++, anything would work at the moment).

    Thank you.

    Continue reading...

Compartilhe esta Página