IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

3D Python Discussion :

[OpenGL] Appliquer une texture sur deux triangles [Python 3.X]


Sujet :

3D Python

  1. #1
    Membre actif
    Homme Profil pro
    Développeur Web
    Inscrit en
    Avril 2012
    Messages
    133
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2012
    Messages : 133
    Points : 208
    Points
    208
    Par défaut [OpenGL] Appliquer une texture sur deux triangles
    Bonjour,

    J’essaye d’appliquer une texture sur deux triangles.

    Pour se faire, j’ai suivi les tutoriels suivants :

    - https://learnopengl.com/Getting-started/Textures
    - https://robertvandeneynde.be/parascolaire/3D.fr.html
    Lors de l’affichage de mes deux triangles, si j’utilise glDrawArrays(GL_TRIANGLES, 0, 6) j’ai un seul triangle qui s’affiche et si j’utilise glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0) alors aucun triangle s’affiche.

    Vous trouverez mon code complet ci-dessous, je suis à court d’idées alors merci de votre aide.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    #!coding: utf-8
    from __future__ import print_function, division
     
    from OpenGL.GL import *
    from OpenGL.GL import shaders
    import ctypes
    import pygame
     
    from vecutils import * # téléchargez vecutils ici
     
    vertexShader = """
    #version 330 core
    layout (location = 0) in vec3 attrPosition;
    layout (location = 1) in vec3 attrColor;
    layout (location = 2) in vec2 attrTexCoords;
     
    out vec3 vsColor;
    out vec2 vsTexCoords;
     
    void main()
    {
        gl_Position = vec4(attrPosition, 1.0);
        vsColor = attrColor;
        vsTexCoords = attrTexCoords;
    }   
    """
     
    fragmentShader = """
    #version 330 core
    uniform sampler2D texUniform;
     
    in vec3 vsColor;
    in vec2 vsTexCoords;
     
    out vec4 FragColor;
    void main()
    {
        FragColor = vec4(texture(texUniform, vsTexCoords).rgb, 1);
    }
    """
     
     
    NB_POSITION_AXES = 3
    NB_COLOR_AXES = 3
    NB_TEX_COORDS_AXES = 2
     
    vertices1 = farray([
        # positions        # colors         # texture coords
         0.5,  0.5, 0.0,   1.0, 0.0, 0.0,   1.0, 1.0,   # top right
         0.5, -0.5, 0.0,   0.0, 1.0, 0.0,   1.0, 0.0,   # bottom right
        -0.5, -0.5, 0.0,   0.0, 0.0, 1.0,   0.0, 0.0,   # bottom left
        -0.5,  0.5, 0.0,   1.0, 1.0, 0.0,   0.0, 1.0,   # top left 
    ])
     
    indices1 = farray([
        0, 1, 3, # first triangle
        1, 2, 3,  # second triangle
    ])
     
    def createObject(shaderProgram, vertices, indices):
     
        # Create a new VAO (Vertex Array Object) 
        VAO = glGenVertexArrays(1)
        VBO = glGenBuffers(1)
        EBO = glGenBuffers(1)
     
        # Bind the Vertex Array Object first
        glBindVertexArray(VAO)
     
        # Bind the Vertex Buffer
        glBindBuffer(GL_ARRAY_BUFFER, VBO)
        glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vertices), vertices, GL_STATIC_DRAW)
     
        # Bind the Entity Buffer
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(indices), indices, GL_STATIC_DRAW)
     
        # Configure vertex attribute
     
        # - Position attribute
        glVertexAttribPointer(0, NB_POSITION_AXES, GL_FLOAT, GL_FALSE, 8 * ctypes.sizeof(ctypes.c_float), ctypes.c_void_p(0))
        glEnableVertexAttribArray(0)
     
        # - Color attribute
        glVertexAttribPointer(1, NB_COLOR_AXES, GL_FLOAT, GL_FALSE, 8 * ctypes.sizeof(ctypes.c_float), ctypes.c_void_p(3 * ctypes.sizeof(ctypes.c_float)))
        glEnableVertexAttribArray(1)
     
        # - Texture coordinates attribute
        glVertexAttribPointer(2, NB_TEX_COORDS_AXES, GL_FLOAT, GL_FALSE, 8 * ctypes.sizeof(ctypes.c_float), ctypes.c_void_p(6 * ctypes.sizeof(ctypes.c_float)))
        glEnableVertexAttribArray(2)
     
     
        # Texture
     
        texture = glGenTextures(1)
        glBindTexture(GL_TEXTURE_2D, texture)
        # Set the texture wrapping parameters
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) # Set texture wrapping to GL_REPEAT (default wrapping method)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
        # Set texture filtering parameters
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
     
        image = pygame.image.load('images/wall.jpg').convert_alpha()
        imageData = pygame.image.tostring(image, 'RGBA', 1)
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.get_width(), image.get_height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData)
        glGenerateMipmap(GL_TEXTURE_2D)
     
        # Unbind the VAO
        glBindVertexArray(0)
     
        # Unbind the VBO
        glBindBuffer(GL_ARRAY_BUFFER, 0)
        glDisableVertexAttribArray(0)
        glDisableVertexAttribArray(1)
        glDisableVertexAttribArray(2)
     
        # Unbind the EBO
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)
     
        return VAO, texture
     
    def initDisplay(shaderProgram):
        glEnable(GL_DEPTH_TEST)
     
        glUseProgram(shaderProgram)
        textureUniformIndex = glGetUniformLocation(shaderProgram, 'texUniform')
        glUniform1i(textureUniformIndex, 0)
     
    def prepareDisplay():
        glClearColor(0.2, 0.3, 0.3, 1.0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
     
    def drawObject(shaderProgram, VAO, texture):
     
        glActiveTexture(GL_TEXTURE0)
        glBindTexture(GL_TEXTURE_2D, texture)
     
        glUseProgram(shaderProgram)
        glBindVertexArray(VAO)
        #glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0)
        glDrawArrays(GL_TRIANGLES, 0, 6)
     
    def display():
        glBindVertexArray(0)
        glUseProgram(0)
     
    def main():
        pygame.init()
        screen = pygame.display.set_mode((800, 600), pygame.OPENGL|pygame.DOUBLEBUF)
     
        shaderProgram = shaders.compileProgram(
            shaders.compileShader(vertexShader, GL_VERTEX_SHADER),
            shaders.compileShader(fragmentShader, GL_FRAGMENT_SHADER))
     
        initDisplay(shaderProgram)
     
        VAO, texture = createObject(shaderProgram, vertices1, indices1)
     
        clock = pygame.time.Clock()
     
        done = False
        while not done:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    done = True
     
            prepareDisplay()
            drawObject(shaderProgram, VAO, texture)
            display()
            pygame.display.flip()
            clock.tick(60)
     
    if __name__ == '__main__':
        try:
            main()
        finally:
            pygame.quit()

  2. #2
    Responsable 2D/3D/Jeux


    Avatar de LittleWhite
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Mai 2008
    Messages
    26 855
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels

    Informations forums :
    Inscription : Mai 2008
    Messages : 26 855
    Points : 218 551
    Points
    218 551
    Billets dans le blog
    118
    Par défaut
    Bonjour,

    Pour avoir deux textures, il faut le pseudo code suivant :
    activer texture 1
    dessiner triangle 1

    activer texture 2
    dessiner triangle 2
    Pour le glDrawElements(), il faut un tampon d'indices.
    Finalement, veuillez noter que Developpez.com propose des traductions de tutoriels OpenGL, notamment LearnOpenGL.
    Vous souhaitez participer à la rubrique 2D/3D/Jeux ? Contactez-moi

    Ma page sur DVP
    Mon Portfolio

    Qui connaît l'erreur, connaît la solution.

  3. #3
    Membre actif
    Homme Profil pro
    Développeur Web
    Inscrit en
    Avril 2012
    Messages
    133
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2012
    Messages : 133
    Points : 208
    Points
    208
    Par défaut
    Salut et merci pour ta réponse.

    Alors ici c est le problème inverse. J ai une seule texture que je souhaite appliquer sur deux triangles. Un seul des deux triangles apparaît.

    Concernant ta remarque :
    Pour le glDrawElements(), il faut un tampon d'indices.

    Si tu fais référence à un EBO il est bel et bien implémenté tel que montré dans le code ci dessus. Après peut-être que je ne comprend pas bien ta remarque auquel cas je suis tout ouïe.

    ++

    Edit :

    Voici la version corrigé :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    #!coding: utf-8
    from __future__ import print_function, division
     
    from OpenGL.GL import *
    from OpenGL.GL import shaders
    import ctypes
    import pygame
    import numpy as np
     
    from vecutils import *
     
    vertexShader = """
    #version 330 core
    layout (location = 0) in vec3 attrPosition;
    layout (location = 1) in vec3 attrColor;
    layout (location = 2) in vec2 attrTexCoords;
     
    out vec3 vsColor;
    out vec2 vsTexCoords;
     
    void main()
    {
        gl_Position = vec4(attrPosition, 1.0);
        vsColor = attrColor;
        vsTexCoords = attrTexCoords;
    }   
    """
     
    fragmentShader = """
    #version 330 core
    uniform sampler2D texUniform;
     
    in vec3 vsColor;
    in vec2 vsTexCoords;
     
    out vec4 FragColor;
    void main()
    {
        FragColor = vec4(texture(texUniform, vsTexCoords).rgb, 1);
    }
    """
     
     
    NB_POSITION_AXES = 3
    NB_COLOR_AXES = 3
    NB_TEX_COORDS_AXES = 2
     
    vertices1 = farray([
        # positions        # colors         # texture coords
         0.5,  0.5, 0.0,   1.0, 0.0, 0.0,   1.0, 1.0,   # top right
         0.5, -0.5, 0.0,   0.0, 1.0, 0.0,   1.0, 0.0,   # bottom right
        -0.5, -0.5, 0.0,   0.0, 0.0, 1.0,   0.0, 0.0,   # bottom left
        -0.5,  0.5, 0.0,   1.0, 1.0, 0.0,   0.0, 1.0,   # top left 
    ])
     
    indices1 = np.array([
        0, 1, 3, # first triangle
        1, 2, 3,  # second triangle
    ], dtype=np.uint32)
     
    def createObject(shaderProgram, vertices, indices):
     
        # Create a new VAO (Vertex Array Object) 
        VAO = glGenVertexArrays(1)
        VBO = glGenBuffers(1)
        EBO = glGenBuffers(1)
     
        # Bind the Vertex Array Object first
        glBindVertexArray(VAO)
     
        # Bind the Vertex Buffer
        glBindBuffer(GL_ARRAY_BUFFER, VBO)
        glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vertices), vertices, GL_STATIC_DRAW)
     
        # Bind the Entity Buffer
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(indices), indices, GL_STATIC_DRAW)
     
        # Configure vertex attribute
     
        # - Position attribute
        attrPositionIndex = glGetAttribLocation(shaderProgram, 'attrPosition')
        if (attrPositionIndex != -1):
            glVertexAttribPointer(attrPositionIndex, NB_POSITION_AXES, GL_FLOAT, GL_FALSE, 8 * ctypes.sizeof(ctypes.c_float), ctypes.c_void_p(0))
            glEnableVertexAttribArray(attrPositionIndex)
     
        # - Color attribute
        attrColorIndex = glGetAttribLocation(shaderProgram, 'attrColor') # doesn't work ?
        if (attrColorIndex != -1):
            glVertexAttribPointer(attrColorIndex, NB_COLOR_AXES, GL_FLOAT, GL_FALSE, 8 * ctypes.sizeof(ctypes.c_float), ctypes.c_void_p(3 * ctypes.sizeof(ctypes.c_float)))
            glEnableVertexAttribArray(attrColorIndex)
     
        # - Texture coordinates attribute
        attrTexCoordsIndex = glGetAttribLocation(shaderProgram, 'attrTexCoords')
        if (attrTexCoordsIndex != -1):
            glVertexAttribPointer(attrTexCoordsIndex, NB_TEX_COORDS_AXES, GL_FLOAT, GL_FALSE, 8 * ctypes.sizeof(ctypes.c_float), ctypes.c_void_p(6 * ctypes.sizeof(ctypes.c_float)))
            glEnableVertexAttribArray(attrTexCoordsIndex)
     
     
        # Texture
     
        texture = glGenTextures(1)
        glBindTexture(GL_TEXTURE_2D, texture)
        # Set the texture wrapping parameters
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) # Set texture wrapping to GL_REPEAT (default wrapping method)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
        # Set texture filtering parameters
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
     
        image = pygame.image.load('images/wall.jpg').convert_alpha()
        imageData = pygame.image.tostring(image, 'RGBA', 1)
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.get_width(), image.get_height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData)
        glGenerateMipmap(GL_TEXTURE_2D)
     
        # Unbind the VAO
        glBindVertexArray(0)
     
        # Unbind the VBO
        glBindBuffer(GL_ARRAY_BUFFER, 0)
        if (attrPositionIndex != -1):
            glDisableVertexAttribArray(attrPositionIndex)
        if (attrColorIndex != -1):
            glDisableVertexAttribArray(attrColorIndex)
        if (attrTexCoordsIndex != -1):
            glDisableVertexAttribArray(attrTexCoordsIndex)
     
        # Unbind the EBO
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)
     
        return VAO, texture
     
    def initDisplay(shaderProgram):
        glEnable(GL_DEPTH_TEST)
     
        glUseProgram(shaderProgram)
        textureUniformIndex = glGetUniformLocation(shaderProgram, 'texUniform')
        glUniform1i(textureUniformIndex, 0)
     
    def prepareDisplay():
        glClearColor(0.2, 0.3, 0.3, 1.0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
     
    def drawObject(shaderProgram, VAO, texture):
     
        glActiveTexture(GL_TEXTURE0)
        glBindTexture(GL_TEXTURE_2D, texture)
     
        glUseProgram(shaderProgram)
        glBindVertexArray(VAO)
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, ctypes.c_void_p(0))
        #glDrawArrays(GL_TRIANGLE_STRIP, 0, 4)
     
    def display():
        glBindVertexArray(0)
        glUseProgram(0)
     
    def main():
        pygame.init()
        screen = pygame.display.set_mode((800, 600), pygame.OPENGL|pygame.DOUBLEBUF)
     
        shaderProgram = shaders.compileProgram(
            shaders.compileShader(vertexShader, GL_VERTEX_SHADER),
            shaders.compileShader(fragmentShader, GL_FRAGMENT_SHADER))
     
        initDisplay(shaderProgram)
     
        VAO, texture = createObject(shaderProgram, vertices1, indices1)
     
        clock = pygame.time.Clock()
     
        done = False
        while not done:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    done = True
     
            prepareDisplay()
            drawObject(shaderProgram, VAO, texture)
            display()
            pygame.display.flip()
            clock.tick(60)
     
    if __name__ == '__main__':
        try:
            main()
        finally:
            pygame.quit()

  4. #4
    Responsable 2D/3D/Jeux


    Avatar de LittleWhite
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Mai 2008
    Messages
    26 855
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels

    Informations forums :
    Inscription : Mai 2008
    Messages : 26 855
    Points : 218 551
    Points
    218 551
    Billets dans le blog
    118
    Par défaut
    En lisant le code, je n'ai pas réussi à trouver ce qui pouvait boguer. Vous pouvez vous aider avec des débogueurs graphiques comme gDEBugger/AMD gDEBugger
    Vous souhaitez participer à la rubrique 2D/3D/Jeux ? Contactez-moi

    Ma page sur DVP
    Mon Portfolio

    Qui connaît l'erreur, connaît la solution.

  5. #5
    Membre actif
    Homme Profil pro
    Développeur Web
    Inscrit en
    Avril 2012
    Messages
    133
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2012
    Messages : 133
    Points : 208
    Points
    208
    Par défaut
    Salut, il fallait utiliser un entier pour les indices et cvoid pour glDrawElements.

  6. #6
    Responsable 2D/3D/Jeux


    Avatar de LittleWhite
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Mai 2008
    Messages
    26 855
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels

    Informations forums :
    Inscription : Mai 2008
    Messages : 26 855
    Points : 218 551
    Points
    218 551
    Billets dans le blog
    118
    Par défaut
    Cool. Je m'étais plus concentré sur les paramètres de glDraw* et sur les positions (notamment leur ordre, mais j'allais pas imaginer que Python utilise d'office les float).
    Vous souhaitez participer à la rubrique 2D/3D/Jeux ? Contactez-moi

    Ma page sur DVP
    Mon Portfolio

    Qui connaît l'erreur, connaît la solution.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Appliquer une fonction sur deux vecteur avec apply ? mais comment
    Par comme de bien entendu dans le forum R
    Réponses: 0
    Dernier message: 08/08/2018, 17h35
  2. Appliquer une texture sur un icosaèdre
    Par nouriami dans le forum Images
    Réponses: 10
    Dernier message: 26/11/2013, 15h27
  3. Appliquer une texture sur un cercle
    Par bakman dans le forum ActionScript 3
    Réponses: 0
    Dernier message: 01/07/2010, 14h24
  4. Une texture sur plusieurs triangles
    Par mm2405 dans le forum OpenGL
    Réponses: 5
    Dernier message: 17/12/2007, 10h15
  5. appliquer une texture sur une grille
    Par franc82 dans le forum OpenGL
    Réponses: 6
    Dernier message: 02/03/2007, 16h17

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo