The SDL forums have moved to discourse.libsdl.org.
This is just a read-only archive of the previous forums, to keep old links working.


SDL Forum Index
SDL
Simple Directmedia Layer Forums
Opengl context doesn't work outside the main.
Lolilolight


Joined: 07 Jun 2014
Posts: 17
Hi,
I'm trying to use SDL in my 2D and 3D framework but it fails to create the opengl context when I want to create it outside the main :

Code:

Window::Window(VideoMode mode, const std::string & title, Uint32 style, unsigned int bitsPerPixel, const sf::ContextSettings& settings) :
m_window          (nullptr),
m_context       (nullptr),
m_frameTimeLimit(sf::Time::Zero),
m_size          (0, 0)
{
    m_window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, mode.getWidth(), mode.getHeight(), style);
    context = SDL_GL_CreateContext(m_window);   
}


I get a window with a transparent background and nothing is drawn.

[/code]
Lolilolight


Joined: 07 Jun 2014
Posts: 17
I've frogot to mention it (sorry), my plateform is ubuntu 14.04 64 bits.
Re: Opengl context doesn't work outside the main.
AlexRou


Joined: 31 Jan 2014
Posts: 57
Can you create a minimal test program that causes it and upload the source code for that? So like its easier to figure out what went wrong where than to go through your entire source codes.

Lolilolight wrote:
Hi,
I'm trying to use SDL in my 2D and 3D framework but it fails to create the opengl context when I want to create it outside the main :

Code:

Window::Window(VideoMode mode, const std::string & title, Uint32 style, unsigned int bitsPerPixel, const sf::ContextSettings& settings) :
m_window          (nullptr),
m_context       (nullptr),
m_frameTimeLimit(sf::Time::Zero),
m_size          (0, 0)
{
    m_window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, mode.getWidth(), mode.getHeight(), style);
    context = SDL_GL_CreateContext(m_window);   
}


I get a window with a transparent background and nothing is drawn.

[/code]
Lolilolight


Joined: 07 Jun 2014
Posts: 17
Ok, here is a code :

Code:

#ifndef ODFAEG_WINDOW_HPP
#define ODFAEG_WINDOW_HPP
#include "export.hpp"
#include <thread>
#include "videoMode.h"
#include <SFML/Window/GlResource.hpp>
#include <SFML/Window/ContextSettings.hpp>
#include <SFML/System/Vector2.hpp>
#include <SFML/System/NonCopyable.hpp>
#include <SFML/System/String.hpp>
#include <SFML/System/Sleep.hpp>
#include <SFML/System/Clock.hpp>
#include <SFML/System/Err.hpp>
#include <queue>
#include <SDL2/SDL_syswm.h>
namespace odfaeg
{
namespace priv
{
    class GlContext;
    class SDLWindowImpl;
}
}
////////////////////////////////////////////////////////////
/// \brief Window that serves as a target for OpenGL rendering
///
////////////////////////////////////////////////////////////
namespace odfaeg {
class ODFAEG_GRAPHICS_API Window : sf::GlResource, sf::NonCopyable
{
public :

    ////////////////////////////////////////////////////////////
    /// \brief Default constructor
    ///
    /// This constructor doesn't actually create the window,
    /// use the other constructors or call "create" to do so.
    ///
    ////////////////////////////////////////////////////////////
    Window();

    ////////////////////////////////////////////////////////////
    /// \brief Construct a new window
    ///
    /// This constructor creates the window with the size and pixel
    /// depth defined in \a mode. An optional style can be passed to
    /// customize the look and behaviour of the window (borders,
    /// title bar, resizable, closable, ...). If \a style contains
    /// Style::Fullscreen, then \a mode must be a valid video mode.
    ///
    /// The fourth parameter is an optional structure specifying
    /// advanced OpenGL context settings such as antialiasing,
    /// depth-buffer bits, etc.
    ///
    /// \param mode     Video mode to use (defines the width, height and depth of the rendering area of the window)
    /// \param title    Title of the window
    /// \param style    Window style
    /// \param settings Additional settings for the underlying OpenGL context
    ///
    Window(VideoMode mode, const std::string& title, Uint32 style, unsigned int bitsPerPixel, const sf::ContextSettings& settings);

    ////////////////////////////////////////////////////////////
    /// \brief Destructor
    ///
    /// Closes the window and free all the resources attached to it.
    ///
    ////////////////////////////////////////////////////////////
    virtual ~Window();

    ////////////////////////////////////////////////////////////
    /// \brief Create (or recreate) the window
    ///
    /// If the window was already created, it closes it first.
    /// If \a style contains Style::Fullscreen, then \a mode
    /// must be a valid video mode.
    ///
    /// \param mode     Video mode to use (defines the width, height and depth of the rendering area of the window)
    /// \param title    Title of the window
    /// \param style    Window style
    /// \param settings Additional settings for the underlying OpenGL context
    ///
    ////////////////////////////////////////////////////////////
    void create(VideoMode mode, const std::string& title, ::Uint32 style, unsigned int bitsPerPixel, const sf::ContextSettings& settings);

    ////////////////////////////////////////////////////////////
    /// \brief Close the window and destroy all the attached resources
    ///
    /// After calling this function, the sf::Window instance remains
    /// valid and you can call create() to recreate the window.
    /// All other functions such as pollEvent() or display() will
    /// still work (i.e. you don't have to test isOpen() every time),
    /// and will have no effect on closed windows.
    ///
    ////////////////////////////////////////////////////////////
    void close();

    ////////////////////////////////////////////////////////////
    /// \brief Tell whether or not the window is open
    ///
    /// This function returns whether or not the window exists.
    /// Note that a hidden window (setVisible(false)) is open
    /// (therefore this function would return true).
    ///
    /// \return True if the window is open, false if it has been closed
    ///
    ////////////////////////////////////////////////////////////
    bool isOpen() const;

    ////////////////////////////////////////////////////////////
    /// \brief Get the settings of the OpenGL context of the window
    ///
    /// Note that these settings may be different from what was
    /// passed to the constructor or the create() function,
    /// if one or more settings were not supported. In this case,
    /// SFML chose the closest match.
    ///
    /// \return Structure containing the OpenGL context settings
    ///
    ////////////////////////////////////////////////////////////
    const sf::ContextSettings& getSettings() const;

    ////////////////////////////////////////////////////////////
    /// \brief Pop the event on top of the event queue, if any, and return it
    ///
    /// This function is not blocking: if there's no pending event then
    /// it will return false and leave \a event unmodified.
    /// Note that more than one event may be present in the event queue,
    /// thus you should always call this function in a loop
    /// to make sure that you process every pending event.
    /// \code
    /// sf::Event event;
    /// while (window.pollEvent(event))
    /// {
    ///    // process event...
    /// }
    /// \endcode
    ///
    /// \param event Event to be returned
    ///
    /// \return True if an event was returned, or false if the event queue was empty
    ///
    /// \see waitEvent
    ///
    ////////////////////////////////////////////////////////////
    bool pollEvent(SDL_Event& event);

    ////////////////////////////////////////////////////////////
    /// \brief Wait for an event and return it
    ///
    /// This function is blocking: if there's no pending event then
    /// it will wait until an event is received.
    /// After this function returns (and no error occured),
    /// the \a event object is always valid and filled properly.
    /// This function is typically used when you have a thread that
    /// is dedicated to events handling: you want to make this thread
    /// sleep as long as no new event is received.
    /// \code
    /// sf::Event event;
    /// if (window.waitEvent(event))
    /// {
    ///    // process event...
    /// }
    /// \endcode
    ///
    /// \param event Event to be returned
    ///
    /// \return False if any error occured
    ///
    /// \see pollEvent
    ///
    ////////////////////////////////////////////////////////////
    bool waitEvent(SDL_Event& event);

    ////////////////////////////////////////////////////////////
    /// \brief Get the position of the window
    ///
    /// \return Position of the window, in pixels
    ///
    /// \see setPosition
    ///
    ////////////////////////////////////////////////////////////
    sf::Vector2i getPosition() const;

    ////////////////////////////////////////////////////////////
    /// \brief Change the position of the window on screen
    ///
    /// This function only works for top-level windows
    /// (i.e. it will be ignored for windows created from
    /// the handle of a child window/control).
    ///
    /// \param position New position, in pixels
    ///
    /// \see getPosition
    ///
    ////////////////////////////////////////////////////////////
    void setPosition(const sf::Vector2i& position);

    ////////////////////////////////////////////////////////////
    /// \brief Get the size of the rendering region of the window
    ///
    /// The size doesn't include the titlebar and borders
    /// of the window.
    ///
    /// \return Size in pixels
    ///
    /// \see setSize
    ///
    ////////////////////////////////////////////////////////////
    sf::Vector2u getSize() const;

    ////////////////////////////////////////////////////////////
    /// \brief Change the size of the rendering region of the window
    ///
    /// \param size New size, in pixels
    ///
    /// \see getSize
    ///
    ////////////////////////////////////////////////////////////
    void setSize(const sf::Vector2u size);

    ////////////////////////////////////////////////////////////
    /// \brief Change the title of the window
    ///
    /// \param title New title
    ///
    /// \see setIcon
    ///
    ////////////////////////////////////////////////////////////
    void setTitle(const std::string& title);

    ////////////////////////////////////////////////////////////
    /// \brief Change the window's icon
    ///
    /// \a pixels must be an array of \a width x \a height pixels
    /// in 32-bits RGBA format.
    ///
    /// The OS default icon is used by default.
    ///
    /// \param width  Icon's width, in pixels
    /// \param height Icon's height, in pixels
    /// \param pixels Pointer to the array of pixels in memory
    ///
    /// \see setTitle
    ///
    ////////////////////////////////////////////////////////////
    void setIcon(SDL_Surface* icon);

    ////////////////////////////////////////////////////////////
    /// \brief Show or hide the window
    ///
    /// The window is shown by default.
    ///
    /// \param visible True to show the window, false to hide it
    ///
    ////////////////////////////////////////////////////////////
    void setVisible(bool visible);

    ////////////////////////////////////////////////////////////
    /// \brief Enable or disable vertical synchronization
    ///
    /// Activating vertical synchronization will limit the number
    /// of frames displayed to the refresh rate of the monitor.
    /// This can avoid some visual artifacts, and limit the framerate
    /// to a good value (but not constant across different computers).
    ///
    /// Vertical synchronization is disabled by default.
    ///
    /// \param enabled True to enable v-sync, false to deactivate it
    ///
    ////////////////////////////////////////////////////////////
    void setVerticalSyncEnabled(bool enabled);

    ////////////////////////////////////////////////////////////
    /// \brief Show or hide the mouse cursor
    ///
    /// The mouse cursor is visible by default.
    ///
    /// \param visible True to show the mouse cursor, false to hide it
    ///
    ////////////////////////////////////////////////////////////
    void setMouseCursorVisible(bool visible);

    ////////////////////////////////////////////////////////////
    /// \brief Enable or disable automatic key-repeat
    ///
    /// If key repeat is enabled, you will receive repeated
    /// KeyPressed events while keeping a key pressed. If it is disabled,
    /// you will only get a single event when the key is pressed.
    ///
    /// Key repeat is enabled by default.
    ///
    /// \param enabled True to enable, false to disable
    ///
    ////////////////////////////////////////////////////////////
    void setKeyRepeatEnabled(bool enabled);

    ////////////////////////////////////////////////////////////
    /// \brief Limit the framerate to a maximum fixed frequency
    ///
    /// If a limit is set, the window will use a small delay after
    /// each call to display() to ensure that the current frame
    /// lasted long enough to match the framerate limit.
    /// SFML will try to match the given limit as much as it can,
    /// but since it internally uses sf::sleep, whose precision
    /// depends on the underlying OS, the results may be a little
    /// unprecise as well (for example, you can get 65 FPS when
    /// requesting 60).
    ///
    /// \param limit Framerate limit, in frames per seconds (use 0 to disable limit)
    ///
    ////////////////////////////////////////////////////////////
    void setFramerateLimit(unsigned int limit);

    ////////////////////////////////////////////////////////////
    /// \brief Change the joystick threshold
    ///
    /// The joystick threshold is the value below which
    /// no JoystickMoved event will be generated.
    ///
    /// The threshold value is 0.1 by default.
    ///
    /// \param threshold New threshold, in the range [0, 100]
    ///
    ////////////////////////////////////////////////////////////
    void setJoystickThreshold(float threshold);

    ////////////////////////////////////////////////////////////
    /// \brief Activate or deactivate the window as the current target
    ///        for OpenGL rendering
    ///
    /// A window is active only on the current thread, if you want to
    /// make it active on another thread you have to deactivate it
    /// on the previous thread first if it was active.
    /// Only one window can be active on a thread at a time, thus
    /// the window previously active (if any) automatically gets deactivated.
    ///
    /// \param active True to activate, false to deactivate
    ///
    /// \return True if operation was successful, false otherwise
    ///
    ////////////////////////////////////////////////////////////
    bool setActive(bool active = true) const;

    ////////////////////////////////////////////////////////////
    /// \brief Display on screen what has been rendered to the window so far
    ///
    /// This function is typically called after all OpenGL rendering
    /// has been done for the current frame, in order to show
    /// it on screen.
    ///
    ////////////////////////////////////////////////////////////
    void display();

    ////////////////////////////////////////////////////////////
    /// \brief Get the OS-specific handle of the window
    ///
    /// The type of the returned handle is sf::WindowHandle,
    /// which is a typedef to the handle type defined by the OS.
    /// You shouldn't need to use this function, unless you have
    /// very specific stuff to implement that SFML doesn't support,
    /// or implement a temporary workaround until a bug is fixed.
    ///
    /// \return System handle of the window
    ///
    ////////////////////////////////////////////////////////////
    SDL_SysWMinfo getSystemHandle() const;

protected :

    ////////////////////////////////////////////////////////////
    /// \brief Function called after the window has been created
    ///
    /// This function is called so that derived classes can
    /// perform their own specific initialization as soon as
    /// the window is created.
    ///
    ////////////////////////////////////////////////////////////
    virtual void onCreate();

    ////////////////////////////////////////////////////////////
    /// \brief Function called after the window has been resized
    ///
    /// This function is called so that derived classes can
    /// perform custom actions when the size of the window changes.
    ///
    ////////////////////////////////////////////////////////////
    virtual void onResize();

private:

    ////////////////////////////////////////////////////////////
    /// \brief Processes an event before it is sent to the user
    ///
    /// This function is called every time an event is received
    /// from the internal window (through pollEvent or waitEvent).
    /// It filters out unwanted events, and performs whatever internal
    /// stuff the window needs before the event is returned to the
    /// user.
    ///
    /// \param event Event to filter
    ///
    ////////////////////////////////////////////////////////////
    bool filterEvent(const SDL_Event& event);

    ////////////////////////////////////////////////////////////
    /// \brief Perform some common internal initializations
    ///
    ////////////////////////////////////////////////////////////
    void initialize();

    ////////////////////////////////////////////////////////////
    /// \brief Return the next window event available
    ///
    /// If there's no event available, this function calls the
    /// window's internal event processing function.
    /// The \a block parameter controls the behaviour of the function
    /// if no event is available: if it is true then the function
    /// doesn't return until a new event is triggered; otherwise it
    /// returns false to indicate that no event is available.
    ///
    /// \param event Event to be returned
    /// \param block Use true to block the thread until an event arrives
    ///
    ////////////////////////////////////////////////////////////
    bool popEvent(SDL_Event& event);
    void pushEvent(const SDL_Event& event);
    //void processJoystickEvents();

    ////////////////////////////////////////////////////////////
    /// \brief Get the OS-specific handle of the window
    ///
    /// \return Handle of the window
    ///
    ////////////////////////////////////////////////////////////
    //virtual SDL_SysWMinfo getSystemHandle() const = 0;

    ////////////////////////////////////////////////////////////
    // Member data
    ////////////////////////////////////////////////////////////
    SDL_Window*           m_window;           ///< Platform-specific implementation of the window
    priv::GlContext*      m_context;        ///< Platform-specific implementation of the OpenGL context
    sf::Clock             m_clock;          ///< Clock for measuring the elapsed time between frames
    sf::Time              m_frameTimeLimit; ///< Current framerate limit
    sf::Vector2u          m_size;           ///< Current size of the window
    float treshold;
    std::queue<SDL_Event> m_events;
    SDL_GLContext context;
};

} // namespace sf

#endif // ODFAEG_WINDOW_HPP

#include "../../../include/odfaeg/Graphics/window.h"
#include "glContext.h"
#include <iostream>
namespace odfaeg {
namespace
{
    const Window* fullscreenWindow = nullptr;
}

////////////////////////////////////////////////////////////
Window::Window() :
m_window         (nullptr),
m_context       (nullptr),
m_frameTimeLimit(sf::Time::Zero),
m_size          (0, 0)
{

}

////////////////////////////////////////////////////////////
Window::Window(VideoMode mode, const std::string & title, Uint32 style, unsigned int bitsPerPixel, const sf::ContextSettings& settings) :
m_window          (nullptr),
m_context       (nullptr),
m_frameTimeLimit(sf::Time::Zero),
m_size          (0, 0)
{
    create(mode, title, style, bitsPerPixel, settings);
}

////////////////////////////////////////////////////////////
Window::~Window()
{
    close();
}


////////////////////////////////////////////////////////////
void Window::create(VideoMode mode, const std::string& title, Uint32 style, unsigned int bitsPerPixel, const sf::ContextSettings& settings)
{
    // Destroy the previous window implementation
    close();

    // Fullscreen style requires some tests
    if (style & SDL_WINDOW_FULLSCREEN)
    {
        // Make sure there's not already a fullscreen window (only one is allowed)
        if (fullscreenWindow)
        {
            sf::err() << "Creating two fullscreen windows is not allowed, switching to windowed mode" << std::endl;
            style &= ~SDL_WINDOW_FULLSCREEN;
        }
        else
        {
            // Make sure that the chosen video mode is compatible
            if (!mode.isValid())
            {
                sf::err() << "The requested video mode is not available, switching to a valid mode" << std::endl;
                mode = VideoMode::getFullscreenModes()[0];
            }

            // Update the fullscreen window
            fullscreenWindow = this;
        }
    }

    // Recreate the window implementation
    m_window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, mode.getWidth(), mode.getHeight(), style);
   // std::cout<<"create : "<<std::endl;
    // Recreate the context

    context = SDL_GL_CreateContext(m_window);


}


////////////////////////////////////////////////////////////
void Window::close()
{
    if (m_window)
        SDL_DestroyWindow(m_window);
    m_window = nullptr;
    // Update the fullscreen window
    if (this == fullscreenWindow)
        fullscreenWindow = nullptr;
}


////////////////////////////////////////////////////////////
bool Window::isOpen() const
{
    return m_window != nullptr;
}


////////////////////////////////////////////////////////////
const sf::ContextSettings& Window::getSettings() const
{
    static const sf::ContextSettings empty(0, 0, 0);

    return m_context ? m_context->getSettings() : empty;
}


////////////////////////////////////////////////////////////
bool Window::pollEvent(SDL_Event& event)
{
    SDL_PollEvent(&event);
}


////////////////////////////////////////////////////////////
bool Window::waitEvent(SDL_Event& event)
{
    SDL_WaitEvent(&event);
    if (m_window)
    {
        return filterEvent(event);
    }
    else
    {
        return false;
    }
}


////////////////////////////////////////////////////////////
sf::Vector2i Window::getPosition() const
{
    return m_window ? getPosition() : sf::Vector2i();
}


////////////////////////////////////////////////////////////
void Window::setPosition(const sf::Vector2i& position)
{
    if (m_window)
        SDL_SetWindowPosition(m_window, position.x, position.y);
}


////////////////////////////////////////////////////////////
sf::Vector2u Window::getSize() const
{
    return m_size;
}


////////////////////////////////////////////////////////////
void Window::setSize(const sf::Vector2u size)
{
    if (m_window)
        SDL_SetWindowSize(m_window, size.x, size.y);
}


////////////////////////////////////////////////////////////
void Window::setTitle(const std::string& title)
{
    if (m_window)
        SDL_SetWindowTitle(m_window, title.c_str());
}


////////////////////////////////////////////////////////////
void Window::setIcon(SDL_Surface* icon)
{
    if (m_window)
        SDL_SetWindowIcon(m_window, icon);
}


////////////////////////////////////////////////////////////
void Window::setVisible(bool visible)
{
    if (m_window) {
        if (visible)
            SDL_ShowWindow(m_window);
        else
            SDL_HideWindow(m_window);
    }
}


////////////////////////////////////////////////////////////
void Window::setVerticalSyncEnabled(bool enabled)
{
    if (setActive())
        m_context->setVerticalSyncEnabled(enabled);
}


////////////////////////////////////////////////////////////
void Window::setMouseCursorVisible(bool visible)
{
    if (m_window)
        SDL_ShowCursor(visible);
}


////////////////////////////////////////////////////////////
void Window::setKeyRepeatEnabled(bool enabled)
{
    //Not more avalaible with SDL2.
    /*if (m_impl)
       SDL_EnableKeyRepeat(10, 10);*/
}


////////////////////////////////////////////////////////////
void Window::setFramerateLimit(unsigned int limit)
{
    if (limit > 0)
        m_frameTimeLimit = sf::seconds(1.f / limit);
    else
        m_frameTimeLimit = sf::Time::Zero;
}




////////////////////////////////////////////////////////////
bool Window::setActive(bool active) const
{
    if (m_context)
    {
        if (m_context->setActive(active))
        {
            return true;
        }
        else
        {
            sf::err() << "Failed to activate the window's context" << std::endl;
            return false;
        }
    }
    else
    {
        return false;
    }
}


////////////////////////////////////////////////////////////
void Window::display()
{
    // Display the backbuffer on screen
    if (setActive())
        m_context->display();

    // Limit the framerate if needed
    if (m_frameTimeLimit != sf::Time::Zero)
    {
        sleep(m_frameTimeLimit - m_clock.getElapsedTime());
        m_clock.restart();
    }
}


////////////////////////////////////////////////////////////
SDL_SysWMinfo Window::getSystemHandle() const
{
    SDL_SysWMinfo sysInfo;
    SDL_VERSION(&sysInfo.version); //Set SDL version
    return sysInfo;
}


////////////////////////////////////////////////////////////
void Window::onCreate()
{
    // Nothing by default
}


////////////////////////////////////////////////////////////
void Window::onResize()
{
    // Nothing by default
}


////////////////////////////////////////////////////////////
bool Window::filterEvent(const SDL_Event& event)
{
    // Notify resize events to the derived class
    /*if (event.window.event == SDL_WINDOWEVENT_RESIZED)
    {
        // Cache the new size
        int width, height;
        SDL_GetWindowSize(m_window, &width, &height);
        m_size.x = width;
        m_size.y = height;

        // Notify the derived class
        onResize();
    }*/

    return true;
}


////////////////////////////////////////////////////////////
void Window::initialize()
{
    // Setup default behaviours (to get a consistent behaviour across different implementations)
    setVisible(true);
    setMouseCursorVisible(true);
    setVerticalSyncEnabled(false);
    setKeyRepeatEnabled(true);

    // Get and cache the initial size of the window
    int width, height;
    SDL_GetWindowSize(m_window, &width, &height);
    m_size.x = width;
    m_size.y = height;
    // Reset frame time
    m_clock.restart();

    // Activate the window
    setActive();

    // Notify the derived class
    onCreate();
}


////////////////////////////////////////////////////////////
bool Window::popEvent(SDL_Event& event)
{
    // If the event queue is empty, let's first check if new events are available from the OS
    if (m_events.empty())
    {
        while (m_events.empty())
        {
            sleep(sf::milliseconds(10));
        }
    }

    // Pop the first event of the queue, if it is not empty
    if (!m_events.empty())
    {
        event = m_events.front();
        m_events.pop();

        return true;
    }

    return false;
}
////////////////////////////////////////////////////////////
void Window::pushEvent(const SDL_Event& event)
{
    m_events.push(event);
}

} // namespace sf

odfaeg::VideoMode mode(800, 600, 32);

    sf::ContextSettings settings(32, 32, 4, 3, 0);
    odfaeg::Window window2(mode, "test", SDL_WINDOW_OPENGL, 32, settings);
    glClearColor(0.f, 0.f, 0.f, 1.f);
    while (window2.isOpen()) {
        SDL_Event event;
        while(window2.pollEvent(event)) {
            if (event.window.event == SDL_WINDOWEVENT_CLOSE) {
                window2.close();
            }
        }
        if (window2.isOpen()) {
            glClear(GL_COLOR_BUFFER_BIT);
            glBegin(GL_TRIANGLES);
            glVertex2f(0.f, 1.f);
            glVertex2f(-1.f, 0.f);
            glVertex2f(1.f, 0.f);
            glEnd();
            window2.display();
        }
    }



No mean to share the gl context between threads like the SFML library does. :/

But I've switched to SDL because, SDL seems to support more exotic plateforms.

SDL fails to get the desktop mode, the function return 0 but the pointer with the current display mode is not affected, here is the code of my the class videomode :

Code:

#ifndef ODFAEG_VIDEO_MODE
#define ODFAEG_VIDEO_MODE
#include <SDL2/SDL.h>
#include <vector>
namespace odfaeg {
class VideoMode {
public :
    VideoMode(unsigned int width, unsigned int height, unsigned int bitsPerPixels);
    static std::vector<VideoMode> getFullscreenModes();
    unsigned int getWidth();
    unsigned int getHeight();
    unsigned int getBitsPerPixel();
    static VideoMode getDesktopMode();
    bool isValid() const;
private :
    unsigned int width;
    unsigned int height;
    unsigned int bitsPerPixel;
    friend bool operator ==(const VideoMode& left, const VideoMode& right);

    friend bool operator !=(const VideoMode& left, const VideoMode& right);

    friend bool operator <(const VideoMode& left, const VideoMode& right);

    friend bool operator >(const VideoMode& left, const VideoMode& right);

    friend bool operator <=(const VideoMode& left, const VideoMode& right);

    friend bool operator >=(const VideoMode& left, const VideoMode& right);
};

bool operator ==(const VideoMode& left, const VideoMode& right);

bool operator !=(const VideoMode& left, const VideoMode& right);

bool operator <(const VideoMode& left, const VideoMode& right);

bool operator >(const VideoMode& left, const VideoMode& right);

bool operator <=(const VideoMode& left, const VideoMode& right);

bool operator >=(const VideoMode& left, const VideoMode& right);
}
#endif // ODFAEG_VIDEO_MODE

#include "../../../include/odfaeg/Graphics/videoMode.h"
#include <algorithm>
#include <iostream>
namespace odfaeg {
    VideoMode::VideoMode(unsigned int width, unsigned int height, unsigned int bitsPerPixel) :
        width(width), height (height), bitsPerPixel(bitsPerPixel) {

    }
    std::vector<VideoMode> VideoMode::getFullscreenModes() {
        std::vector<VideoMode> vModes;
        SDL_DisplayMode* current;
        for (unsigned int i = 0; SDL_GetNumVideoDisplays(); ++i) {
            int error = SDL_GetNumDisplayModes(i);
            if (error == 0) {
                for (unsigned int j = 0; j < SDL_GetNumDisplayModes(i); j++) {
                    int should_be_zero = SDL_GetDisplayMode(i, j, current);
                    if (should_be_zero == 0) {
                        VideoMode mode (static_cast<unsigned int>(current->w), static_cast<unsigned int>(current->h), static_cast<unsigned int>(current->format));
                        if (std::find(vModes.begin(), vModes.end(), mode) == vModes.end())
                            vModes.push_back(mode);
                    }
                }
            }
        }
        return vModes;
    }
    VideoMode VideoMode::getDesktopMode() {
        SDL_DisplayMode* current;
        for (unsigned int i = 0; i < SDL_GetNumVideoDisplays(); i++) {
            int error = SDL_GetDesktopDisplayMode(i, current);

            if (error == 0) {
                return VideoMode (static_cast<unsigned int>(current->w), static_cast<unsigned int>(current->h), static_cast<unsigned int>(current->format));
            }
        }
    }
    unsigned int VideoMode::getWidth() {
        return width;
    }
    unsigned int VideoMode::getHeight() {
        return height;
    }
    unsigned int VideoMode::getBitsPerPixel() {
        return bitsPerPixel;
    }
    ////////////////////////////////////////////////////////////
    bool VideoMode::isValid() const
    {
        const std::vector<VideoMode>& modes = getFullscreenModes();

        return std::find(modes.begin(), modes.end(), *this) != modes.end();
    }
    ////////////////////////////////////////////////////////////
    bool operator ==(const VideoMode& left, const VideoMode& right)
    {
        return (left.width        == right.width)        &&
               (left.height       == right.height)       &&
               (left.bitsPerPixel == right.bitsPerPixel);
    }


    ////////////////////////////////////////////////////////////
    bool operator !=(const VideoMode& left, const VideoMode& right)
    {
        return !(left == right);
    }


    ////////////////////////////////////////////////////////////
    bool operator <(const VideoMode& left, const VideoMode& right)
    {
        if (left.bitsPerPixel == right.bitsPerPixel)
        {
            if (left.width == right.width)
            {
                return left.height < right.height;
            }
            else
            {
                return left.width < right.width;
            }
        }
        else
        {
            return left.bitsPerPixel < right.bitsPerPixel;
        }
    }


    ////////////////////////////////////////////////////////////
    bool operator >(const VideoMode& left, const VideoMode& right)
    {
        return right < left;
    }


    ////////////////////////////////////////////////////////////
    bool operator <=(const VideoMode& left, const VideoMode& right)
    {
        return !(right < left);
    }


    ////////////////////////////////////////////////////////////
    bool operator >=(const VideoMode& left, const VideoMode& right)
    {
    return !(left < right);
    }

}

Did I do something wrong ?

Or it is an SDL bug ?
Lolilolight


Joined: 07 Jun 2014
Posts: 17
Here is a more minimal code, it gives me a transparent window :

Code:

#include <SDL2/SDL.h>
#include <SFML/OpenGL.hpp>
#include <string>
class Window {
    public :
    Window (std::string title, int width, int height, int bitsPerPixel, Uint32 style) {
        m_window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, bitsPerPixel);
        m_context = SDL_GL_CreateContext(m_window);
    }
    void close() {
        SDL_GL_DeleteContext(m_context);
        SDL_DestroyWindow(m_window);
        m_window = nullptr;
    }
    void display() {
        SDL_GL_SwapWindow(m_window);
    }
    bool isOpen() {
        return m_window != nullptr;
    }
    private :
        SDL_Window* m_window;
        SDL_GLContext m_context;
};
int main(void)
{

    Window window("test", 800, 600, 32, SDL_WINDOW_OPENGL);
    glClearColor(0.f, 0.f, 0.f, 1.f);
    while (window.isOpen()) {
        SDL_Event event;
        while(SDL_PollEvent(&event)) {
            if (event.window.event == SDL_WINDOWEVENT_CLOSE) {
                window.close();
            }
        }
        if (window.isOpen()) {
            glClear(GL_COLOR_BUFFER_BIT);
            glBegin(GL_TRIANGLES);
            glVertex2f(0.f, 1.f);
            glVertex2f(-1.f, 0.f);
            glVertex2f(1.f, 0.f);
            glEnd();
            window.display();
        }
    }
[/code]
AlexRou


Joined: 31 Jan 2014
Posts: 57
Soo err first of all did you do a SDL_Init()?

Secondly after SDL_Init() and before SDL_CreateWindow and SDL_CreateContex you need to set some GL settings like

SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 2 );
SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 1 );
SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE );

Then to display its

SDL_GL_SwapWindow( m_Window );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

Not m_context->Display

I think you need to start from scratch with a simple program to just display something so that you learn how to use SDL before you do complicated things. Also it might be a bad idea to include SFML headers in a SDL program incase they mess each other up.


Code:

#include <SDL2/SDL.h>
#include <GL/gl.h>

int main( int argc, char* args[] )
{
   if( SDL_Init( SDL_INIT_EVERYTHING ) != 0 )
   {
      //error
   }

   SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 2 );
   SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 1 );
   SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE );
   SDL_GL_SetAttribute( SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG );
   SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
   SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, 1 );
   SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, 8 );
   SDL_GL_SetAttribute( SDL_GL_ACCELERATED_VISUAL, 1 );

   SDL_Window* window = SDL_CreateWindow( "Test Window",
                                          SDL_WINDOWPOS_CENTERED,
                                          SDL_WINDOWPOS_CENTERED,
                                          800, 600,
                                          SDL_WINDOW_OPENGL
                                        );

   SDL_GLContext GLContext = SDL_GL_CreateContext( window );
   glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );

   glViewport( 0, 0, 800, 600 );
   /* change to the projection matrix and set our viewing volume. */
   glMatrixMode( GL_PROJECTION );
   glLoadIdentity();

   glOrtho( 0, 800, 600, 0, -1, 1 );

   /* Make sure we're chaning the model view and not the projection */
   glMatrixMode( GL_MODELVIEW );

   /* Reset The View */
   glLoadIdentity();
   glPushMatrix();

   SDL_Event* event = new SDL_Event;
   bool quit = false;

   while( !quit )
   {
      while( !SDL_PollEvent( event ) )
      {
            if( event->type == SDL_QUIT )
                quit = true;
      }

      glMatrixMode( GL_MODELVIEW );
      glPopMatrix();
      glPushMatrix();

      glBegin( GL_TRIANGLE_STRIP );

      glColor4f( 1.0f, 1.0f, 1.0f, 1.0f );
      glVertex3f( -100, -100, 0.0f );
      glVertex3f( 100, -100, 0.0f );
      glVertex3f( -100, 100, 0.0f );
      glVertex3f( 100, 100, 0.0f );

      glEnd();

      SDL_GL_SwapWindow( window );
      glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
   }

    SDL_Quit();

   return 0;
}
Lolilolight


Joined: 07 Jun 2014
Posts: 17
I've done everything that you said but the problem still remains :

Code:

#include <SDL2/SDL.h>
#include <string>
#include <GL/gl.h>
#include <iostream>
class Window {
    public :
    Window (std::string title, int width, int height, int bitsPerPixel, Uint32 style) {
        m_window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, bitsPerPixel);
        m_context = SDL_GL_CreateContext(m_window);
    }
    void close() {
        SDL_GL_DeleteContext(m_context);
        SDL_DestroyWindow(m_window);
        m_window = nullptr;
    }
    void display() {
        SDL_GL_SwapWindow(m_window);
    }
    bool isOpen() {
        return m_window != nullptr;
    }
    ~Window() {
        close();
    }
    private :
        SDL_Window* m_window;
        SDL_GLContext m_context;
};
int main(void)
{
    if(SDL_Init( SDL_INIT_EVERYTHING ) != 0) {
        std::cout<<"error"<<std::endl;
    }

    Window window("test", 800, 600, 32, SDL_WINDOW_OPENGL);
    glClearColor(0.f, 0.f, 0.f, 1.f);
    while (window.isOpen()) {
        SDL_Event event;
        while(SDL_PollEvent(&event)) {
            if (event.window.event == SDL_WINDOWEVENT_CLOSE) {
                window.close();
            }
        }
        if (window.isOpen()) {
            glClear(GL_COLOR_BUFFER_BIT);
            glBegin(GL_TRIANGLES);
            glVertex2f(0.f, 1.f);
            glVertex2f(-1.f, 0.f);
            glVertex2f(1.f, 0.f);
            glEnd();
            window.display();
        }
    }
    SDL_Quit();
    return 0;
AlexRou


Joined: 31 Jan 2014
Posts: 57
Your main function must be int main( int argc, char* args[] )

And you must link libSDL2main and libSDL2

Lolilolight wrote:
I've done everything that you said but the problem still remains :

Code:

#include <SDL2/SDL.h>
#include <string>
#include <GL/gl.h>
#include <iostream>
class Window {
    public :
    Window (std::string title, int width, int height, int bitsPerPixel, Uint32 style) {
        m_window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, bitsPerPixel);
        m_context = SDL_GL_CreateContext(m_window);
    }
    void close() {
        SDL_GL_DeleteContext(m_context);
        SDL_DestroyWindow(m_window);
        m_window = nullptr;
    }
    void display() {
        SDL_GL_SwapWindow(m_window);
    }
    bool isOpen() {
        return m_window != nullptr;
    }
    ~Window() {
        close();
    }
    private :
        SDL_Window* m_window;
        SDL_GLContext m_context;
};
int main(void)
{
    if(SDL_Init( SDL_INIT_EVERYTHING ) != 0) {
        std::cout<<"error"<<std::endl;
    }

    Window window("test", 800, 600, 32, SDL_WINDOW_OPENGL);
    glClearColor(0.f, 0.f, 0.f, 1.f);
    while (window.isOpen()) {
        SDL_Event event;
        while(SDL_PollEvent(&event)) {
            if (event.window.event == SDL_WINDOWEVENT_CLOSE) {
                window.close();
            }
        }
        if (window.isOpen()) {
            glClear(GL_COLOR_BUFFER_BIT);
            glBegin(GL_TRIANGLES);
            glVertex2f(0.f, 1.f);
            glVertex2f(-1.f, 0.f);
            glVertex2f(1.f, 0.f);
            glEnd();
            window.display();
        }
    }
    SDL_Quit();
    return 0;
Lolilolight


Joined: 07 Jun 2014
Posts: 17
And here with your code, it works when I create the context in the function main but when I want to encapsulate it in a class => nothing.

[code]

/*#include "myApplication.h"
#include "odfaeg/Graphics/convexShape.h"

#include "odfaeg/Graphics/renderWindow.h"
#include "glCheck.h"
#include <fstream>
#include "odfaeg/Network/aes.h"
#include "odfaeg/Graphics/3D/cube.h"
#include "odfaeg/Graphics/window.h"
#include <glew.h>
#include <SFML/OpenGL.hpp>
#include <functional>*/
#include <SDL2/SDL.h>
#include <string>
#include <GL/gl.h>
#include <iostream>
class Window {
public :
Window (std::string title, int width, int height, int bitsPerPixel, Uint32 style) {
SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 2 );
SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 1 );
SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE );
SDL_GL_SetAttribute( SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG );
SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, 1 );
SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, 8 );
SDL_GL_SetAttribute( SDL_GL_ACCELERATED_VISUAL, 1 );
m_window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, bitsPerPixel);
m_context = SDL_GL_CreateContext(m_window);
}
void close() {
SDL_GL_DeleteContext(m_context);
SDL_DestroyWindow(m_window);
m_window = nullptr;
}
void display() {
SDL_GL_SwapWindow(m_window);
}
bool isOpen() {
return m_window != nullptr;
}
~Window() {
close();
}
private :
SDL_Window* m_window;
SDL_GLContext m_context;
};
int main(void)
{
if(SDL_Init( SDL_INIT_EVERYTHING ) != 0) {
std::cout<<"error"<<std::endl;
}
Window window("test", 800, 600, 32, SDL_WINDOW_OPENGL);
glClearColor(0.f, 0.f, 0.f, 1.f);
glViewport( 0, 0, 800, 600 );
/* change to the projection matrix and set our viewing volume. */
glMatrixMode( GL_PROJECTION );
glLoadIdentity();

glOrtho( 0, 800, 600, 0, -1, 1 );

/* Make sure we're chaning the model view and not the projection */
glMatrixMode( GL_MODELVIEW );

/* Reset The View */
glLoadIdentity();
glPushMatrix();
while (window.isOpen()) {
SDL_Event event;
while(SDL_PollEvent(&event)) {
if (event.window.event == SDL_WINDOWEVENT_CLOSE) {
window.close();
}
}
glMatrixMode( GL_MODELVIEW );
glPopMatrix();
glPushMatrix();

glBegin( GL_TRIANGLE_STRIP );

glColor4f( 1.0f, 1.0f, 1.0f, 1.0f );
glVertex3f( -100, -100, 0.0f );
glVertex3f( 100, -100, 0.0f );
glVertex3f( -100, 100, 0.0f );
glVertex3f( 100, 100, 0.0f );

glEnd();

window.display();
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
}
SDL_Quit();
return 0;

/*MyAppli app(sf::VideoMode(800, 600), "Test odfaeg");
return app.exec();*/
}
AlexRou


Joined: 31 Jan 2014
Posts: 57
There shouldn't be a reason for it to not work in a class unless there is something wrong with the class in the first place.

Try printing SDL_GetError() after every single call to a SDL function.

Then after SDL_GL_SwapWindow add this:

GLenum error;

while( (error = glGetError()) != GL_NO_ERROR )
{
char buffer[256];
sprintf( buffer, "\nGL ERROR: %s", gluErrorString( error ) );
cout << buffer;
}

Then just see if any error pops up.
Lolilolight


Joined: 07 Jun 2014
Posts: 17
I've solved my problem, I gived a wrong parameter. (bitsPerPixels instead of the style)

But it fails to activate a gl3 context :
No good framebuffers found. GL 3.x disabled.
AlexRou


Joined: 31 Jan 2014
Posts: 57
Was that message from SDL_GetError or gluErrorString?

Whats your opengl version from glxinfo | grep version
And what SDL_GL_SetAttribute are you using?

Lolilolight wrote:
I've solved my problem, I gived a wrong parameter. (bitsPerPixels instead of the style)

But it fails to activate a gl3 context :
No good framebuffers found. GL 3.x disabled.
Lolilolight


Joined: 07 Jun 2014
Posts: 17
glxinfo | grep version
server glx version string: 1.4
client glx version string: 1.4
GLX version: 1.4
OpenGL core profile version string: 3.3 (Core Profile) Mesa 10.1.3
OpenGL core profile shading language version string: 3.30
OpenGL version string: 3.0 Mesa 10.1.3
OpenGL shading language version string: 1.30

And for the attributes I use this ones :

GL_DEPTH_SIZE, settings.depthBits,
GL_STENCIL_SIZE, settings.stencilBits,
GL_SAMPLE_BUFFERS, settings.antialiasingLevel > 0,
GL_SAMPLES, settings.antialiasingLevel,
GL_RED_SIZE, 8,
GL_GREEN_SIZE, 8,
GL_BLUE_SIZE, 8,
GL_ALPHA_SIZE, bitsPerPixel == 32 ? 8 : 0,
GL_DOUBLEBUFFER, 1,
GL_CONTEXT_MAJOR_VERSION_ARB, static_cast<int>(m_settings.majorVersion),
GL_CONTEXT_MINOR_VERSION_ARB, static_cast<int>(m_settings.minorVersion),
GL_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB
Lolilolight


Joined: 07 Jun 2014
Posts: 17
I think they are some attribute missing for opengl3..., but, anyway I have another problem with FBOs so..., I think I'll repass on SFML for the moment.
AlexRou


Joined: 31 Jan 2014
Posts: 57
Try getting things working without the classes first then only add it to the class so its easier to debug, but if you really want to go back to SFML its up to you.

The only attributes you need to care for opengl 3 is

GL_CONTEXT_MAJOR_VERSION_ARB
GL_CONTEXT_MINOR_VERSION_ARB
GL_CONTEXT_PROFILE_MASK_ARB

Also try getting it to work with pure SDL incase its one of the other libraries messing up. Referencing your other thread, did you make sure that the texture is properly generated and in GL_RGBA8 format?

Lolilolight wrote:
I think they are some attribute missing for opengl3..., but, anyway I have another problem with FBOs so..., I think I'll repass on SFML for the moment.
AlexRou


Joined: 31 Jan 2014
Posts: 57
BTW read up on what triggers the invalid operation error so you know what to look out for. http://oss.sgi.com/projects/ogl-sample/registry/EXT/framebuffer_object.txt (just crtl F invalid_operation)

AlexRou wrote:
Try getting things working without the classes first then only add it to the class so its easier to debug, but if you really want to go back to SFML its up to you.

The only attributes you need to care for opengl 3 is

GL_CONTEXT_MAJOR_VERSION_ARB
GL_CONTEXT_MINOR_VERSION_ARB
GL_CONTEXT_PROFILE_MASK_ARB

Also try getting it to work with pure SDL incase its one of the other libraries messing up. Referencing your other thread, did you make sure that the texture is properly generated and in GL_RGBA8 format?

Lolilolight wrote:
I think they are some attribute missing for opengl3..., but, anyway I have another problem with FBOs so..., I think I'll repass on SFML for the moment.