Contenu | Rechercher | Menus

Annonce

Si vous avez des soucis pour rester connecté, déconnectez-vous puis reconnectez-vous depuis ce lien en cochant la case
Me connecter automatiquement lors de mes prochaines visites.

À propos de l'équipe du forum.

#1 Le 17/11/2011, à 09:33

Hibou57

[Tuto] Example d'application OpenGL en GTK + Python, C, C++

Hello les people,

GLUT, c’est pas le pied, ou GLUT c’est pas glop, comme disait l’autre.

Heureusement, GTK peut fournir des contextes OpenGL, ce qui signifie qu’il est possible d’utiliser simplement GTK au lieu de GLUT, pour l’interface utilisateur, ce qui est quand même plus propre et s’intègre mieux, surtout sur Debian ou Ubuntu.

Alors petit script Python qui pourra servir de point de départ aux personnes intéressées, et ça vaut le meilleur des tutos. Pour les dépendance, assurez vous seulement d’avoir le paquet PyGtkGLExt. Si vous ne l’avez pas, son installations installera toutes les autres dépendances manquantes dans la foulée.

Le programme d’exemple est volontairement minimaliste, il ne fait qu’afficher un carré blanc, mais c’est assez pour savoir où vous devez changer quoi pour vous même.

Téléchargement : test_opengl_gtk.py.gz

Ou copiez/collez depuis ici :

#! /usr/bin/env python
# -*- coding: utf-8 -*-

""" Sample OpenGL/GTK application using Python and pygtkglext. """

# How to use: ensure PyGtkGLExt is installed. Any other dependencies will
# come with it, so no need to list all of these. When done, run this script.
# If this works and you saw a window with a white square drawn inside, that's
# OK, and you can go on studying this source to get a starting point with
# OpenGL in GTK applications.


# Configuration
# ============================================================================

MAIN_WINDOW_TITLE     = "OpenGL/GTK Test"
MINIMAL_WINDOW_WIDTH  = 640
MINIMAL_WINDOW_HEIGHT = 480


# Imports
# ============================================================================

from OpenGL.GL import    \
    glBegin,             \
    glClear,             \
    GL_COLOR_BUFFER_BIT, \
    GL_DEPTH_BUFFER_BIT, \
    glEnd,               \
    glLoadIdentity,      \
    glMatrixMode,        \
    GL_MODELVIEW,        \
    GL_PROJECTION,       \
    GL_QUADS,            \
    glTranslate,         \
    glVertex,            \
    glViewport

from OpenGL.GLU import \
    gluPerspective

import gtk
import gtk.gdkgl as gdkgl
import gtk.gtkgl as gtkgl


# On draw
# ============================================================================

def on_draw (area, _):

    """ Handles an `expose-event` event. Draws in the test OpenGL drawing
        area.
    """

    drawable = area.get_gl_drawable ()
    context = area.get_gl_context ()

    if not drawable.gl_begin (context):
        return

    allocation = area.get_allocation ()
    viewport_width = float (allocation.width)
    viewport_height = float (allocation.height)

    # gluPerspective does not accept named parameters.
    # Use variable instead, for readability.
    # Z negative forward oriented.

    aspect =  viewport_width / viewport_height
    fovy   =  35.0 # The one which looks to most natural.
    z_near =   2.0 # Enough for a moderately sized sample model.
    z_far  =  -2.0 # Idem.

    # glTranslate does not accept named parameters.
    # Use variable instead, for readability.
    # Z positive forward oriented.

    projection_dx =  0.0
    projection_dy =  0.0
    projection_dz = -3.0

    # Reset picture.
    glViewport (0, 0, int (viewport_width), int (viewport_height))
    glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    # Model defined in default coordinates.
    glMatrixMode (GL_MODELVIEW)
    glLoadIdentity ()

    # Projection using perspective and a few units backward.
    glMatrixMode (GL_PROJECTION)
    glLoadIdentity ()
    gluPerspective (fovy, aspect, z_near, z_far)
    glTranslate (projection_dx, projection_dy, projection_dz)
    # Use the line below instead of the two above, for non perspective view.
    # glOrtho (-aspect, +aspect, -1.0, +1.0, zNear, zFar)

    # Draw a 1x1 square center on origin and on the x*y plan.
    # x*y*z, Z negative forward oriented.
    glBegin (GL_QUADS)
    glVertex ( 0.5, -0.5, 0.0)
    glVertex ( 0.5,  0.5, 0.0)
    glVertex (-0.5,  0.5, 0.0)
    glVertex (-0.5, -0.5, 0.0)
    glEnd ()

    drawable.swap_buffers ()

    drawable.gl_end ()

    return True


# On run About Dialog
# ============================================================================

def on_run_about_dialog (_):

    """ Handles a `clicked` event. Open and run an About dialog box. """

    dialog = None

    # On user response
    # ------------------------------------------------------------------------

    def on_user_response (_, response):

        """ Handles a `response` event. Close the dialog box whenever the
            response is either cancel, close or OK.
        """

        if response == gtk.RESPONSE_CANCEL:
            dialog.destroy ()
        elif response == gtk.RESPONSE_CLOSE:
            dialog.destroy ()
        elif response == gtk.RESPONSE_OK:
            dialog.destroy ()

    # Dialog set-up
    # ------------------------------------------------------------------------

    comments = \
        "A sample tutorial and test application\n" + \
        "for OpenGL over GTK."

    dialog = gtk.AboutDialog ()

    dialog.set_name           ("OpenGL/GTK Test Application")
    dialog.set_version        ("v1.0")
    dialog.set_copyright      ("(c) 2011 Douda & Yannick")
    dialog.set_comments       (comments)
    dialog.set_license        ("BSD.")
    dialog.set_website        ('http://bulleforum.net')
    dialog.set_website_label  ("Forum LaBulle (fr)")
    dialog.set_authors        (["Yannick"])
    dialog.set_documenters    (["Nobody"])
    dialog.set_artists        (["Nobody"])
    dialog.set_logo_icon_name ('applications-multimedia')
    dialog.set_program_name   ("OpenGL/GTK Test")

    dialog.connect ('response', on_user_response)

    # Run dialog
    # ------------------------------------------------------------------------

    dialog.run ()


# Run application
# ============================================================================

def run_application ():
    """ Mainly create an OpenGL display area as a GTK widget. Then attach
        event handlers for that area, so that OpenGL events are mapped in our
        GTK application. Then the whole is run as usualy for any GTK
        application.

        See also `on_draw`.
    """

    # Main window
    # ------------------------------------------------------------------------

    window = gtk.Window ()
    window.set_title (MAIN_WINDOW_TITLE)
    window.connect ('destroy', gtk.main_quit)

    # Window content layout box
    # ------------------------------------------------------------------------

    main_box = gtk.VBox (homogeneous=False, spacing=0)
    window.add (main_box)
    main_box.show ()

    # OpenGL display area
    # ------------------------------------------------------------------------

    config = gdkgl.Config (
        mode = (
            gdkgl.MODE_RGBA |
            gdkgl.MODE_DOUBLE |
            gdkgl.MODE_DEPTH))

    area = gtkgl.DrawingArea (config)

    area.set_size_request (
        width=MINIMAL_WINDOW_WIDTH,
        height=MINIMAL_WINDOW_HEIGHT)

    area.connect ('expose-event', on_draw)

    main_box.pack_start (child=area, expand=True)
    area.show ()

    # Bottom buttons box
    # ------------------------------------------------------------------------

    button_box = gtk.HButtonBox ()
    button_box.set_layout (gtk.BUTTONBOX_END)
    main_box.pack_end (child=button_box, expand=False)
    button_box.show ()

    # Quit button
    # ------------------------------------------------------------------------

    button = gtk.Button (stock=gtk.STOCK_QUIT)
    button.connect ('clicked', gtk.main_quit)
    button_box.pack_start (child=button, expand=False)
    button.show ()

    # About dialog button
    # ------------------------------------------------------------------------

    button = gtk.Button (stock=gtk.STOCK_ABOUT)
    button.connect ('clicked', on_run_about_dialog)
    button_box.pack_start (child=button, expand=False)
    button.show ()

    # Raise main window
    # ------------------------------------------------------------------------

    window.show ()

    # Run event loop
    # ------------------------------------------------------------------------

    gtk.main ()

# Module's entry point
# ============================================================================

if __name__ == '__main__':

    run_application ()

-- EDIT 2011-11-26 --
Source Python modifié pour passer la validation `pylint` avec la configuration par défaut. Le lien de téléchargement a aussi été modifié, car le nom du source Python a été changé dans le même temps.

Dernière modification par Hibou57 (Le 26/11/2011, à 11:45)


Hajimemashteeeee… \(^o^)/ Tachikoma desu (^_^;)
Le saviez‑vous : le j’m’en foutisme est la cause de la plupart des fléaux du monde contemporain.
Mangez des standards : un grand bol de Standard tous les matins, et vous débutez la journée en pleine forme !
bulleforum.net — Forum de discussions, La Bulle (papotage de la vie courante ou choses trop sérieuses)

Hors ligne

#2 Le 18/11/2011, à 18:26

snake-d12

Re : [Tuto] Example d'application OpenGL en GTK + Python, C, C++

Salut, est ce que tu peux m'envoyer le même code en c++ ?? stp

Hors ligne

#3 Le 20/11/2011, à 18:09

Hibou57

Re : [Tuto] Example d'application OpenGL en GTK + Python, C, C++

En C++, non, pour deux raisons : il n’existe pas de version C++ de libgtkglext (pas trouvé de libgtkglextmm en tous les cas), et je n’ai pas envie d’installer gtkmm.

Mais comme ça semble intéresser une personne au moins, j’ai refait une version C, collant autant que possible à la version Python, ce qui est intéressant pour comparer point par point les différence entre la version C et la version Python. Et un peu plus tard, je ferai une version Ada.

Téléchargement : test-opengl-gtk.c.gz

Ou copié/collé :

// Sample and test application for OpenGL in GTK
// =============================================
// How to use
// ----------
// Ensure `libgtkglext1-dev` is installed. Any other dependencies will come 
// with it, so no need to list all of these. When done, compile and run this
// application. If this works and you saw a window with a white square drawn
// inside, that's OK, and you can go on studying this source to get a starting
// point with OpenGL in GTK applications.
//
// Instructions to build
// ---------------------
// This program must link with `libgtk-x11-2.0`, `libgdkglext-x11-1.0` and
// `gtkglext-x11-1.0`. Pass `-lgtk-x11-2.0 -lgdkglext-x11-1.0 -lgtkglext-x11-1.0` 
// options to GCC. Additionally, the following should be in your GCC include
// search path (assuming C,  not C++), either via `C_INCLUDE_PATH` or via 
// command line parameters:
//
// - /usr/lib/glib-2.0/include/
// - /usr/lib/gtk-2.0/include/
// - /usr/include/glib-2.0/
// - /usr/include/cairo/
// - /usr/include/pango-1.0/
// - /usr/include/gdk-pixbuf-2.0/
// - /usr/include/atk-1.0/
// - /usr/include/gtk-2.0/
// - /usr/lib/gtkglext-1.0/include/
// - /usr/include/gtkglext-1.0/


// Includes
// ===========================================================================

#include <stdlib.h>
#include <stdio.h>

#include <GL/gl.h>
#include <GL/glu.h>

#include <gtk/gtk.h>
#include <glib-object.h>
#include <gdk/gdkgl.h>
#include <gtk/gtkgl.h>

// Configuration
// ===========================================================================

const gchar* main_window_title   = "OpenGL/GTK Test";
const gint minimal_window_width  = 640;
const gint minimal_window_height = 480;

// On draw
// ===========================================================================

gboolean on_draw (GtkObject* area, GdkEventExpose* event, gpointer data)
/**
 * Handles a `expose-event` signal.
 */
{
   GdkGLDrawable* drawable = gtk_widget_get_gl_drawable (GTK_WIDGET (area));
   GdkGLContext* context = gtk_widget_get_gl_context (GTK_WIDGET (area));

   gboolean status = gdk_gl_drawable_gl_begin (drawable, context);

   if (status == FALSE) {
      return;
   }

   GtkAllocation allocation;
   gtk_widget_get_allocation (GTK_WIDGET (area), &allocation);
   GLdouble viewport_width = (GLdouble) allocation.width;
   GLdouble viewport_height = (GLdouble) allocation.height;

   // Z negative forward oriented.

   GLdouble aspect =  viewport_width / viewport_height;
   GLdouble fovy   =  35.0; // The one which looks to most natural.
   GLdouble zNear  =   2.0; // Enough for a moderately sized sample model.
   GLdouble zFar   =  -2.0; // Idem.

   // Z positive forward oriented.

   GLdouble projection_dx =  0.0;
   GLdouble projection_dy =  0.0;
   GLdouble projection_dz = -3.0;

   // Reset picture.
   glViewport (0, 0, (GLint) viewport_width, (GLint) viewport_height);
   glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

   // Model defined in default coordinates.
   glMatrixMode (GL_MODELVIEW);
   glLoadIdentity ();

   // Projection using perspective and a few units backward.
   glMatrixMode (GL_PROJECTION);
   glLoadIdentity ();
   gluPerspective (fovy, aspect, zNear, zFar);
   glTranslated (projection_dx, projection_dy, projection_dz);
   // Use the line below instead of the two above, for non perspective view.
   // glOrtho (-aspect, +aspect, -1.0, +1.0, zNear, zFar);

   // Draw a 1x1 square center on origin and on the x*y plan.
   // x*y*z, Z negative forward oriented.
   glBegin (GL_QUADS);
   glVertex3d ( 0.5, -0.5, 0.0);
   glVertex3d ( 0.5,  0.5, 0.0);
   glVertex3d (-0.5,  0.5, 0.0);
   glVertex3d (-0.5, -0.5, 0.0);
   glEnd ();

   gdk_gl_drawable_swap_buffers (drawable);

   gdk_gl_drawable_gl_end (drawable);

   return TRUE; // Do not propagate the event.
}

// On run About Dialog
// ===========================================================================

// Request to close the dialog
// ---------------------------------------------------------------------------

void on_user_about_dialog_response
  (GtkDialog* dialog, 
   gint response, 
   gpointer data)
/**
 * Handles a `response` signal.
 */
{
   switch (response) {
      case GTK_RESPONSE_CANCEL:
      case GTK_RESPONSE_CLOSE:
      case GTK_RESPONSE_OK: {
         gtk_widget_destroy (GTK_WIDGET (dialog));
      }
   }
}

// Running the dialog
// ---------------------------------------------------------------------------

void on_run_about_dialog (GtkObject* source, gpointer data)
/**
 * Handles a `clicked` signal.
 */
{

   const gchar* copyright      = "© 2011 Douda & Yannick";
   const gchar* license        = "BSD.";
   const gchar* logo_icon_name = "applications-multimedia";
   const gchar* name           = "OpenGL/GTK Test Application";
   const gchar* program_name   = "OpenGL/GTK Test";
   const gchar* version        = "v1.0";
   const gchar* website        = "http://bulleforum.net";
   const gchar* website_label  = "Forum LaBulle (fr)";
   
   const gchar* comments =
      "A sample tutorial and test \n"
      "for OpenGL over GTK applications.";
   
   const gchar* artists[]     = {"Nobody", NULL};
   const gchar* authors[]     = {"Yannick", NULL};
   const gchar* documenters[] = {"Nobody", NULL};

   // Dialog set-up
   // -------------------------------------------------------------------------

   GtkAboutDialog* dialog = GTK_ABOUT_DIALOG (gtk_about_dialog_new ());

   gtk_about_dialog_set_artists        (dialog, artists);
   gtk_about_dialog_set_authors        (dialog, authors);
   gtk_about_dialog_set_comments       (dialog, comments);
   gtk_about_dialog_set_copyright      (dialog, copyright);
   gtk_about_dialog_set_documenters    (dialog, documenters);
   gtk_about_dialog_set_license        (dialog, license);
   gtk_about_dialog_set_logo_icon_name (dialog, logo_icon_name);
   gtk_about_dialog_set_name           (dialog, name);
   gtk_about_dialog_set_program_name   (dialog, program_name);
   gtk_about_dialog_set_version        (dialog, version);
   gtk_about_dialog_set_website        (dialog, website);
   gtk_about_dialog_set_website_label  (dialog, website_label);

   gtk_signal_connect
     (GTK_OBJECT (dialog), 
      "response", 
      GTK_SIGNAL_FUNC (on_user_about_dialog_response), 
      NULL);

   // Run dialog
   // -------------------------------------------------------------------------

   gtk_dialog_run (GTK_DIALOG (dialog));
}

// Quit application
// ===========================================================================

void on_quit_application (GtkObject* source, gpointer data)
/**
 * Handles a `destroy` or a `clicked` signal.
 */
{
   gtk_main_quit ();
}

// Run application
// ===========================================================================

void run_application ()
/**
 * Mainly create an OpenGL display area as a GTK widget. Then attach event
 * handlers for that area, so that OpenGL events are mapped in our GTK
 * application. Then the whole is run as usualy for any GTK application.
 *
 * See also `on_draw`.
 */
{
   gboolean status;

   // Main window
   // -------------------------------------------------------------------------

   GtkWindow* window = GTK_WINDOW (gtk_window_new (GTK_WINDOW_TOPLEVEL));
   gtk_window_set_title (window, main_window_title);

   gtk_signal_connect
     (GTK_OBJECT (window), 
      "destroy", 
      GTK_SIGNAL_FUNC (on_quit_application), 
      NULL);

   // Window content layout box
   // -------------------------------------------------------------------------

   GtkVBox* main_box = GTK_VBOX (gtk_vbox_new (FALSE, 0));
   gtk_container_add (GTK_CONTAINER (window), GTK_WIDGET (main_box));
   gtk_widget_show (GTK_WIDGET (main_box));

   // OpenGL display area
   // -------------------------------------------------------------------------

   GdkGLConfig* config = gdk_gl_config_new_by_mode
     (GDK_GL_MODE_RGBA |
      GDK_GL_MODE_DOUBLE |
      GDK_GL_MODE_DEPTH);

   GtkDrawingArea* area = GTK_DRAWING_AREA (gtk_drawing_area_new ());

   // Give the area, an owned GL context.
   status = gtk_widget_set_gl_capability
     (GTK_WIDGET (area), 
      config, 
      NULL, 
      TRUE, 
      GDK_GL_RGBA_TYPE);

   gtk_widget_set_size_request
     (GTK_WIDGET (area), 
      minimal_window_width, 
      minimal_window_height);

   if (status == FALSE) {
      fputs ("Failed assign GL capability to the GtkDrawingArea.\n", stderr);
      exit (EXIT_FAILURE);
   }

   gtk_signal_connect
     (GTK_OBJECT (area), 
      "expose-event", 
      GTK_SIGNAL_FUNC (on_draw), 
      NULL);

   gtk_box_pack_start (GTK_BOX (main_box), GTK_WIDGET (area), TRUE, TRUE, 0);
   gtk_widget_show (GTK_WIDGET (area));

   // Bottom buttons box
   // -------------------------------------------------------------------------

   GtkHButtonBox* button_box = GTK_HBUTTON_BOX (gtk_hbutton_box_new ());
   gtk_button_box_set_layout (GTK_BUTTON_BOX (button_box), GTK_BUTTONBOX_END);

   gtk_box_pack_end
     (GTK_BOX (main_box), 
      GTK_WIDGET (button_box), 
      FALSE, 
      FALSE, 
      0);

   gtk_widget_show (GTK_WIDGET (button_box));

   // Quit button
   // -------------------------------------------------------------------------

   GtkButton* button;

   button = GTK_BUTTON (gtk_button_new_from_stock (GTK_STOCK_QUIT));

   gtk_box_pack_start
     (GTK_BOX (button_box), 
      GTK_WIDGET (button), 
      FALSE, 
      FALSE, 
      0);

   gtk_widget_show (GTK_WIDGET (button));

   gtk_signal_connect
     (GTK_OBJECT (button), 
      "clicked", 
      GTK_SIGNAL_FUNC (on_quit_application), 
      NULL);

   // About dialog button
   // -------------------------------------------------------------------------

   button = GTK_BUTTON (gtk_button_new_from_stock (GTK_STOCK_ABOUT));

   gtk_box_pack_start
     (GTK_BOX (button_box), 
      GTK_WIDGET (button), 
      FALSE, 
      FALSE, 
      0);

   gtk_widget_show (GTK_WIDGET (button));

   gtk_signal_connect
     (GTK_OBJECT (button), 
      "clicked", 
      GTK_SIGNAL_FUNC (on_run_about_dialog), 
      NULL);

   // Raise main window
   // -------------------------------------------------------------------------

   gtk_widget_show (GTK_WIDGET (window));

   // Run event loop
   // -------------------------------------------------------------------------

   gtk_main ();
}

// Module's entry point
// ===========================================================================

int main (int arguments_count, char** arguments_list)
{
   gboolean init_status;

   g_type_init ();
   gtk_init (&arguments_count, &arguments_list);
   init_status = gdk_gl_init_check (&arguments_count, &arguments_list);
   
   if (init_status == FALSE) {
      fputs ("Failed to initialize GDKGLExt.\n", stderr);
      return EXIT_FAILURE;
   }

   init_status = gtk_gl_init_check (&arguments_count, &arguments_list);
   
   if (init_status == FALSE) {
      fputs ("Failed to initialize GTKGLExt.\n", stderr);
      return EXIT_FAILURE;
   }

   run_application ();

   return EXIT_SUCCESS;
}

Remarque. C’est bizarre, je n’ai pas eu à lier à libGL. Une librairie peut chainer vers une autre ? Sinon je ne m’explique pas comment c’est possible.

Dernière modification par Hibou57 (Le 20/11/2011, à 18:13)


Hajimemashteeeee… \(^o^)/ Tachikoma desu (^_^;)
Le saviez‑vous : le j’m’en foutisme est la cause de la plupart des fléaux du monde contemporain.
Mangez des standards : un grand bol de Standard tous les matins, et vous débutez la journée en pleine forme !
bulleforum.net — Forum de discussions, La Bulle (papotage de la vie courante ou choses trop sérieuses)

Hors ligne

#4 Le 21/11/2011, à 05:34

snake-d12

Re : [Tuto] Example d'application OpenGL en GTK + Python, C, C++

Je te remercie infiniment pour cet exemple.
Je pense que j'ai réussi à traduire la partie que tu m'a donné en c++, mais il me reste un problème au niveau de la méthode 'get_gl_drawable()', je pense qu'elle retourne toujours un objet 'null'.

voici mon code :

class MyArea : public Gtk::GL::DrawingArea
{
public:
  MyArea();
  virtual ~MyArea();

  bool on_draw(GdkEventExpose *event);

};
MyArea::MyArea(): Gtk::GL::DrawingArea(){

    signal_expose_event().connect(sigc::mem_fun(*this, &MyArea::on_draw));
}

MyArea::~MyArea(){}

bool MyArea::on_draw(GdkEventExpose *event)
{
    Glib::RefPtr<Gdk::GL::Config> glconfig;
    glconfig = Gdk::GL::Config::create(Gdk::GL::MODE_RGB |
                                     Gdk::GL::MODE_DEPTH |
                                    Gdk::GL::MODE_DOUBLE);   

    Glib::RefPtr<Gdk::GL::Context> context = get_gl_context();
    Glib::RefPtr<Gdk::GL::Drawable> drawable = get_gl_drawable();

   // Le problème se situe dans cette partie, car l'objet drwable  retourne toujours false
    if(!drawable)
        return false;

    if (! drawable->gl_begin(context))
        return false;

    set_gl_capability(glconfig);

    // Code OpenGL   

    drawable->swap_buffers();
    drawable->gl_end();
    
    return true;

}

void *gtk_win(void *arg)
{
    g_type_init();
        Gtk::Main app(g_argc, g_argv);
        gtk_init(&arg_counts, &arg_list);
       
        Gtk::Window fenetre;      
        MyArea a;

        fenetre.add(a);
        a.show();

        Gtk::Main::run(fenetre);

    return NULL;
}

merci d'avance.

Hors ligne

#5 Le 21/11/2011, à 11:10

Hibou57

Re : [Tuto] Example d'application OpenGL en GTK + Python, C, C++

Bonjour,

Simple commentaires à la lecture du source :

  • Le gestionnaire du signal "expose-event", tel que spécifié dans la documentation de GTK+, prend trois paramètres. Ici la signature ne correspond pas, elle spécifie une fonction qui n’en prend que deux. Mais je peux me tromper et il s'agit peut-être d’une différence dut au binding C++ de GTK.

  • Si get_gl_drawable retourne toujours NULL, c’est probablement que le GtkDrawingArea n’a put être préparé pour l’affichage OpenGL. Voir à ce sujet l’appel à gtk_widget_set_gl_capability.

  • Puisque drawable est testé, en plus de tester si le drawable renvoyé est NULL, il faudrait aussi tester si le contexte renvoyé est NULL.

  • L’appel à set_gl_capability est mal placé. Cette opération doit être effectuée avant de tenter de récupérer un drawable ou un contexte OpenGL, puisque c’est cette opération qui les prépare. Il est possible de faire autrement, mais le source ne correspond pas non-plus à l’autre méthode possible.

Dernière modification par Hibou57 (Le 21/11/2011, à 11:14)


Hajimemashteeeee… \(^o^)/ Tachikoma desu (^_^;)
Le saviez‑vous : le j’m’en foutisme est la cause de la plupart des fléaux du monde contemporain.
Mangez des standards : un grand bol de Standard tous les matins, et vous débutez la journée en pleine forme !
bulleforum.net — Forum de discussions, La Bulle (papotage de la vie courante ou choses trop sérieuses)

Hors ligne

#6 Le 21/11/2011, à 13:42

snake-d12

Re : [Tuto] Example d'application OpenGL en GTK + Python, C, C++

Salut,

Pour le premier point, la signature de l’évènement expose-event en c++ prend un seul paramètre.
Comme tu as indiqué dans les derniers points, le 'drawable' et 'context' ne sont pas encore prêt pour l'affichage car il faut tout d'abord configurer le 'DrawbleArea' avec le 'set_gl_capability()'. mais lorsque je met le code comme ci dessous, je reçoie le message d'erreur suivant au moment de l’exécution : (<MyArea>:2389:GtkGLExt-CRITICAL **:gtk_widget_set_gl_capability: assertion `!gtk_widget_get_realised(widget)` failed ).

    Glib::RefPtr<Gdk::GL::Config> glconfig;
    glconfig = Gdk::GL::Config::create(Gdk::GL::MODE_RGB |
                                     Gdk::GL::MODE_DEPTH |
                                    Gdk::GL::MODE_DOUBLE);

    // Le problème se situe dans cette partie, en affichant le message d'erreur que j'ai signalé au dessus.
    set_gl_capability(glconfig);


    set_size_request(1280, 480);

    Glib::RefPtr<Gdk::GL::Context> context = get_gl_context();
    Glib::RefPtr<Gdk::GL::Drawable> drawable = get_gl_drawable();



    std::cout<<"First Time"<<std::endl;

    if(!drawable)
        return false;

    if (! drawable->gl_begin(context))
        return false;

    // Code OpenGL   

    drawable->swap_buffers();
    drawable->gl_end();

Hors ligne

#7 Le 21/11/2011, à 16:59

Hibou57

Re : [Tuto] Example d'application OpenGL en GTK + Python, C, C++

Quelque chose semble être tenté trop tard. Il faudrait essayer de repousser set_gl_capability le plus en amont possible, et peut‑être avant que les gestionnaires d’événements ne soient fixés.

Voir : gtkforums.com/viewtopic.php?f=3&t=55204
Qui renvoie à : GtkWidget.html#gtk-widget-set-events
Qui dit : 

Le lien ci-dessus a écrit :

Sets the event mask (see GdkEventMask) for a widget. The event mask determines which events a widget will receive. Keep in mind that different widgets have different default event masks, and by changing the event mask you may disrupt a widget's functionality, so be careful. This function must be called while a widget is unrealized

Il n’est pas dit que l’erreur est exactement similaire, mais on peut dire sans se tromper, que set_gl_capability est appelé trop tard, et qu’il faudrait l’appeler plus tôt, avant que certaines opérations ne soient effectuées. Reste à savoir lesquelles précisément.

P.S. Pour les gens qui attendent peut-être (et j’espère qu’il y en a), la version Ada, il faut encore patienter.


Hajimemashteeeee… \(^o^)/ Tachikoma desu (^_^;)
Le saviez‑vous : le j’m’en foutisme est la cause de la plupart des fléaux du monde contemporain.
Mangez des standards : un grand bol de Standard tous les matins, et vous débutez la journée en pleine forme !
bulleforum.net — Forum de discussions, La Bulle (papotage de la vie courante ou choses trop sérieuses)

Hors ligne

#8 Le 21/11/2011, à 18:19

snake-d12

Re : [Tuto] Example d'application OpenGL en GTK + Python, C, C++

Oui tu as raison, j'ai mis la déclaration de la 'glConfig' et la 'set_gl_capability()' dans le constructeur et ça bien fonctionné.

MyArea::MyArea():Gtk::GL::DrawingArea() {
    set_size_request(1280, 480);

    Glib::RefPtr<Gdk::GL::Config> glconfig;
    glconfig = Gdk::GL::Config::create(Gdk::GL::MODE_RGB |
                                     Gdk::GL::MODE_DEPTH |
                                    Gdk::GL::MODE_DOUBLE);

    set_gl_capability(glconfig);


    signal_expose_event().connect(sigc::mem_fun(*this, &MyArea::on_draw));

}

merci bcp pour ton aide, ca été vrmt utile smile

Hors ligne