Category Archives: Programming

SFML: text and font

This article is part of a tutorial dedicated to SFML. The reader may consult the other parts of the tutorial by following this link : SFML tutorial.

This example shows load a font and display a text in the window.

/*!
 * \file    main.cpp
 * \brief   start SFML in full screen and display a text (https://www.lucidarme.me/?p=6127)
 * \author  Philippe Lucidarme
 * \version 1.0
 * \date    12/18/2016
 */

// SFML libraries
#include 
#include 

int main()
{
    // _____________________
    // ::: Create window :::

    // Create a window with the same pixel depth as the desktop
    sf::VideoMode desktopMode = sf::VideoMode::getDesktopMode();

    sf::RenderWindow window(sf::VideoMode(  desktopMode.width,
                                            desktopMode.height,
                                            desktopMode.bitsPerPixel),
                            "SFML part 10",
                            sf::Style::Fullscreen);


    // Enable vertical sync. (vsync)
    window.setVerticalSyncEnabled (true);

    // _________________
    // ::: Load font :::

    sf::Font font;
    if (!font.loadFromFile("../example_font.ttf"))
    {
        std::cerr << ".Error while loading font" << std::endl;
        return -1;
    }

    sf::Text text;
    text.setFont(font); // font est un sf::Font
    text.setString(L"www.lucidarme.me");
    text.setCharacterSize(60); // exprimée en pixels, pas en points !
    text.setColor(sf::Color::Black);
    text.setOrigin(text.getLocalBounds().width/2. , text.getLocalBounds().height/2.);

    std::cout << text.getLocalBounds().width << "\t" << text.getLocalBounds().height;
    // _________________
    // ::: Main loop :::

    sf::Clock timer;
    while (window.isOpen())
    {
        // Process events
        sf::Event event;
        while (window.pollEvent(event))
        {
            // Close the window if a key is pressed or if requested
            if (event.type == sf::Event::Closed) window.close();
            if (event.type == sf::Event::KeyPressed) window.close();
        }

        // Clear the window and apply grey background
        window.clear( sf::Color(127,127,127));
        text.setPosition(window.getSize().x/2. , window.getSize().y/2.);
        window.draw(text);
        // Update display and wait for vsync
        window.display();
    }
    return 0;
}

Download from Git

Files, sharders and source codes can be downloaded for GitLab : https://gitlab.com/philippe.lucidarme/sfml_tutorial/tree/master/part_010

<- Back to SFML tutorial main menu

SFML: sound and music

This article is part of a tutorial dedicated to SFML. The reader may consult the other parts of the tutorial by following this link : SFML tutorial.

This example shows how to play music and sound.

/*!
 * \file    main.cpp
 * \brief   Music and sound examples (https://www.lucidarme.me/?p=6127)
 * \author  Philippe Lucidarme
 * \version 1.0
 * \date    12/20/2016
 */

#include 
#include 


// Wait for ms milliseconds
void delay_ms(int ms)
{
    sf::Clock Timer;
    while (Timer.getElapsedTime().asMilliseconds()5;vol--)
    {
        music.setVolume(vol);
        delay_ms(50);
    }

    // Stop music
    std::cout << "Stop music" << std::endl;
    music.stop();
    return 0;
}

Download from Git

Files, sharders and source codes can be downloaded for GitLab : https://gitlab.com/philippe.lucidarme/sfml_tutorial/tree/master/part_009

<- Back to SFML tutorial main menu

SFML: water effect shader

This article is part of a tutorial dedicated to SFML. The reader may consult the other parts of the tutorial by following this link : SFML tutorial.

This shows how to create a “water effect” shader.

/*!
 * \file    main.cpp
 * \brief   apply a water effect shader to a sprite (https://www.lucidarme.me/?p=6127)
 * \author  Philippe Lucidarme (from https://github.com/SFML/SFML/wiki/Source:-HeatHazeShader)
 * \version 1.0
 * \date    12/19/2016
 */

// SFML libraries
#include 
#include 
#include 


int main()
{
    // _____________________
    // ::: Create window :::

    // Create a window with the same pixel depth as the desktop
    sf::VideoMode desktopMode = sf::VideoMode::getDesktopMode();

    sf::RenderWindow window(sf::VideoMode(  desktopMode.width,
                                            desktopMode.height,
                                            desktopMode.bitsPerPixel),
                            "SFML part 8",
                            sf::Style::Fullscreen);

    // Enable vertical sync. (vsync)
    window.setVerticalSyncEnabled (true);



    // ____________________
    // ::: Load texture :::

    // Create texture from PNG file
    sf::Texture texture;
    if (!texture.loadFromFile("../sfml-icon-small.png"))
    {
        std::cerr << "Error while loading texture" << std::endl;
        return -1;
    }
    // Enable the smooth filter. The texture appears smoother so that pixels are less noticeable.
    texture.setSmooth(true);



    // _______________________________________
    // ::: Create sprite and apply texture :::

    // Create the sprite and apply the texture
    sf::Sprite sprite;
    sprite.setTexture(texture);
    sf::FloatRect spriteSize=sprite.getGlobalBounds();
    // Set origin in the middle of the sprite
    sprite.setOrigin(spriteSize.width/2.,spriteSize.height/2.);



    // _______________
    // ::: Shaders :::

    // Check if shaders are available
    if (!sf::Shader::isAvailable())
    {
        std::cerr << "Shader are not available" << std::endl;
        return -1;
    }

    // Load shaders
    sf::Shader shader;
    if (!shader.loadFromFile("../water.frag", sf::Shader::Fragment))
    {
        std::cerr << "Error while shaders" << std::endl;
        return -1;
    }



    // ___________________________
    // ::: Load distortion map :::

    sf::Texture distortionMap;

    if (!distortionMap.loadFromFile("../noiseWater.png"))
    {
        sf::err() << "Error while loading distortion map" << std::endl;
        return -1;
    }

    // It is important to set repeated to true to enable scrolling upwards
    distortionMap.setRepeated(true);
    // Setting smooth to true lets us use small maps even on larger images
    distortionMap.setSmooth(true);

    // Set texture to the shader
    shader.setParameter("currentTexture", sf::Shader::CurrentTexture);
    shader.setParameter("distortionMapTexture", distortionMap);

    // Shader parameters
    float level = .5f;


    // _________________
    // ::: Main loop :::

    sf::Clock timer;
    while (window.isOpen())
    {
        // Process events
        sf::Event event;
        while (window.pollEvent(event))
        {
            // Close the window if a key is pressed or if requested
            if (event.type == sf::Event::Closed) window.close();

            // If a key is pressed
            if (event.type == sf::Event::KeyPressed)
            {
                switch (event.key.code)
                {
                // If escape is pressed, close the application
                case  sf::Keyboard::Escape : window.close(); break;
                // Process the up, down, left and right keys to modify parameters
                case sf::Keyboard::Up :     level -= .005f;    break;
                case sf::Keyboard::Down:    level += .005f;    break;
                default : break;
                }
            }
        }

        if (level>0.8) level=0.8;
        if (level<0.2) level=0.2;

        // Set shader parameters
        shader.setParameter("time", timer.getElapsedTime().asSeconds());
        shader.setParameter("level",level);

        // Clear the window and apply grey background
        window.clear( sf::Color(127,127,127));

        // Draw the sprite and apply shader
        sprite.setPosition(window.getSize().x/2.,window.getSize().y/2.);
        sprite.setScale(2,2);
        window.draw(sprite,&shader);

        // Update display and wait for vsync
        window.display();
    }
    return 0;
}

Download from Git

Files, sharders and source codes can be downloaded for GitLab : https://gitlab.com/philippe.lucidarme/sfml_tutorial/tree/master/part_008

<- Back to SFML tutorial main menu

SFML: heat effect shader

This article is part of a tutorial dedicated to SFML. The reader may consult the other parts of the tutorial by following this link : SFML tutorial.

This example shows how create a heat effect applied to a sprite.

/*!
 * \file    main.cpp
 * \brief   apply a heat shader to a sprite (https://www.lucidarme.me/?p=6127)
 * \author  Philippe Lucidarme (from https://github.com/SFML/SFML/wiki/Source:-HeatHazeShader)
 * \version 1.0
 * \date    12/19/2016
 */

// SFML libraries
#include 
#include 
#include 


int main()
{
    // _____________________
    // ::: Create window :::

    // Create a window with the same pixel depth as the desktop
    sf::VideoMode desktopMode = sf::VideoMode::getDesktopMode();

    sf::RenderWindow window(sf::VideoMode(  desktopMode.width,
                                            desktopMode.height,
                                            desktopMode.bitsPerPixel),
                            "SFML part 7",
                            sf::Style::Fullscreen);

    // Enable vertical sync. (vsync)
    window.setVerticalSyncEnabled (true);



    // ____________________
    // ::: Load texture :::

    // Create texture from PNG file
    sf::Texture texture;
    if (!texture.loadFromFile("../sfml-icon-small.png"))
    {
        std::cerr << "Error while loading texture" << std::endl;
        return -1;
    }
    // Enable the smooth filter. The texture appears smoother so that pixels are less noticeable.
    texture.setSmooth(true);



    // _______________________________________
    // ::: Create sprite and apply texture :::

    // Create the sprite and apply the texture
    sf::Sprite sprite;
    sprite.setTexture(texture);
    sf::FloatRect spriteSize=sprite.getGlobalBounds();
    // Set origin in the middle of the sprite
    sprite.setOrigin(spriteSize.width/2.,spriteSize.height/2.);



    // _______________
    // ::: Shaders :::

    // Check if shaders are available
    if (!sf::Shader::isAvailable())
    {
        std::cerr << "Shader are not available" << std::endl;
        return -1;
    }

    // Load shaders
    sf::Shader shader;
    if (!shader.loadFromFile("../example_001.frag", sf::Shader::Fragment))
    {
        std::cerr << "Error while shaders" << std::endl;
        return -1;
    }



    // ___________________________
    // ::: Load distortion map :::

    sf::Texture distortionMap;

    if (!distortionMap.loadFromFile("../distortion_map.png"))
    {
        sf::err() << "Error while loading distortion map" << std::endl;
        return -1;
    }

    // It is important to set repeated to true to enable scrolling upwards
    distortionMap.setRepeated(true);
    // Setting smooth to true lets us use small maps even on larger images
    distortionMap.setSmooth(true);

    // Set texture to the shader
    shader.setParameter("currentTexture", sf::Shader::CurrentTexture);
    shader.setParameter("distortionMapTexture", distortionMap);

    // Shader parameters
    float distortionFactor = .05f;
    float riseFactor = .2f;


    // _________________
    // ::: Main loop :::

    sf::Clock timer;
    while (window.isOpen())
    {
        // Process events
        sf::Event event;
        while (window.pollEvent(event))
        {
            // Close the window if a key is pressed or if requested
            if (event.type == sf::Event::Closed) window.close();

            // If a key is pressed
            if (event.type == sf::Event::KeyPressed)
            {
                switch (event.key.code)
                {
                // If escape is pressed, close the application
                case  sf::Keyboard::Escape : window.close(); break;

                // Process the up, down, left and right keys to modify parameters
                case sf::Keyboard::Up :     distortionFactor *= 2.f;    break;
                case sf::Keyboard::Down:    distortionFactor /= 2.f;    break;
                case sf::Keyboard::Left:    riseFactor *= 2.f;          break;
                case sf::Keyboard::Right:   riseFactor /= 2.f;          break;
                default : break;
                }
            }
        }

        // Set shader parameters
        shader.setParameter("time", timer.getElapsedTime().asSeconds());
        shader.setParameter("distortionFactor", distortionFactor);
        shader.setParameter("riseFactor", riseFactor);


        // Clear the window and apply grey background
        window.clear( sf::Color(127,127,127));

        // Draw the sprite and apply shader
        sprite.setPosition(window.getSize().x/2.,window.getSize().y/2.);
        sprite.setScale(2,2);
        window.draw(sprite,&shader);

        // Update display and wait for vsync
        window.display();
    }
    return 0;
}

Download from Git

Files, sharders and source codes can be downloaded for GitLab : https://gitlab.com/philippe.lucidarme/sfml_tutorial/tree/master/part_007

<- Back to SFML tutorial main menu

SFML: sprite and shaders

This article is part of a tutorial dedicated to SFML. The reader may consult the other parts of the tutorial by following this link : SFML tutorial.

This example shows how to use shaders. Shaders are programs executed in the GPU (Graphics Processing Unit). The advantage is to release the main processor from this computation.

/*!
 * \file    main.cpp
 * \brief   apply a shaders to a sprite (https://www.lucidarme.me/?p=6127)
 * \author  Philippe Lucidarme
 * \version 1.0
 * \date    12/20/2016
 */

// SFML libraries
#include 
#include 
#include 


// Example 1 : distorsion
// Example 2 : breath
// Example 3 : shaked
// Example 4 : fade
// Example 5 : blur
//#define SHADER_FILENAME         "../example_001.frag"
//#define SHADER_FILENAME         "../example_002.frag"
//#define SHADER_FILENAME         "../example_003.frag"
//#define SHADER_FILENAME         "../example_004.frag"
#define SHADER_FILENAME         "../example_005.frag"

#define     WINDOW_WIDTH    256
#define     WINDOW_HEIGHT   256

int main()
{

    // _____________________
    // ::: Create window :::

    // Create a non resizable window
    sf::RenderWindow window(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), "SFML Shader Example", sf::Style::Titlebar | sf::Style::Close);


    // Create a window size texture and a sprite for the shader
    sf::Texture tex;
    tex.create(WINDOW_WIDTH, WINDOW_HEIGHT);
    sf::Sprite spr(tex);

    // Enable vertical sync. (vsync)
    window.setVerticalSyncEnabled (true);



    // ____________________
    // ::: Load texture :::

    // Create texture from PNG file
    sf::Texture texture;
    if (!texture.loadFromFile("../sfml-icon-small.png"))
    {
        std::cerr << "Error while loading texture" << std::endl;
        return -1;
    }
    // Enable the smooth filter. The texture appears smoother so that pixels are less noticeable.
    texture.setSmooth(true);



    // _______________________________________
    // ::: Create sprite and apply texture :::

    // Create the sprite and apply the texture
    sf::Sprite sprite;
    sprite.setTexture(texture);
    sf::FloatRect spriteSize=sprite.getGlobalBounds();
    // Set origin in the middle of the sprite
    sprite.setOrigin(spriteSize.width/2.,spriteSize.height/2.);



    // _______________
    // ::: Shaders :::

    // Check if shaders are available
    if (!sf::Shader::isAvailable())
    {
        std::cerr << "Shader are not available" << std::endl;
        return -1;
    }

    // Load shaders
    sf::Shader shader;
    if (!shader.loadFromFile(SHADER_FILENAME, sf::Shader::Fragment))
    {
        std::cerr << "Error while shaders" << std::endl;
        return -1;
    }




    // _________________
    // ::: Main loop :::

    sf::Clock time;
    while (window.isOpen())
    {
        // Process events
        sf::Event event;
        while (window.pollEvent(event))
        {
            // Close the window if a key is pressed or if requested
            if (event.type == sf::Event::Closed) window.close();

            // If escape is pressed, close the application
            if (event.type == sf::Event::KeyPressed && event.key.code==sf::Keyboard::Escape) window.close();
        }

        // Set shader parameters
        shader.setParameter("time", time.getElapsedTime().asSeconds());

        // Clear the window and apply grey background
        window.clear( sf::Color(127,127,127));

        // Draw the sprite and apply shader
        sprite.setPosition(window.getSize().x/2.,window.getSize().y/2.);
        window.draw(sprite,&shader);

        // Update display and wait for vsync
        window.display();
    }
    return 0;
}

Download from Git

Files, sharders and source codes can be downloaded for GitLab : https://gitlab.com/philippe.lucidarme/sfml_tutorial/tree/master/part_006

<- Back to SFML tutorial main menu

SFML: shaders

This article is part of a tutorial dedicated to SFML. The reader may consult the other parts of the tutorial by following this link : SFML tutorial.

This example shows how to use shaders. Shaders are programs executed in the GPU (Graphics Processing Unit). The advantage is to release the main processor from this computation.

/*!
 * \file    main.cpp
 * \brief   examples of shaders (https://www.lucidarme.me/?p=6127)
 * \author  Philippe Lucidarme
 * \version 1.0
 * \date    12/18/2016
 */

#include 
#include 

// Examples from http://glslsandbox.com/
// Example 1 : mouse on fire
// Example 2 : scrolling of shapes
// Example 3 : cells
// Example 4 : fire
// Example 5 : moving circles
// Example 6 : smoke
// Example 7 : horizontal scrolling mountains
#define SHADER_FILENAME         "../example_001.frag"
//#define SHADER_FILENAME         "../example_002.frag"
//#define SHADER_FILENAME         "../example_003.frag"
//#define SHADER_FILENAME         "../example_004.frag"
//#define SHADER_FILENAME         "../example_005.frag"
//#define SHADER_FILENAME         "../example_006.frag"
//#define SHADER_FILENAME         "../example_007.frag"


#define     WINDOW_WIDTH    800
#define     WINDOW_HEIGHT   600

int main()
{


    // Create a non resizable window
    sf::RenderWindow window(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT),
                            "SFML Shader Example",
                            sf::Style::Titlebar | sf::Style::Close);


    // Create a window size texture and a sprite for the shader
    sf::Texture tex;
    tex.create(WINDOW_WIDTH, WINDOW_HEIGHT);
    sf::Sprite spr(tex);


    // Create an load the shader from file
    sf::Shader shader;
    shader.loadFromFile(SHADER_FILENAME, sf::Shader::Fragment);
    if (!shader.isAvailable()) {
        std::cout << "The shader is not available\n";
        return -1;
    }


    // Set the resolution parameter (initial window size)
    shader.setParameter("resolution", sf::Vector2f(WINDOW_WIDTH , WINDOW_HEIGHT));


    // Use a timer to obtain the time elapsed
    sf::Clock clk;


   // Main loop
    while (window.isOpen()) {
        // Event handling
        sf::Event event;

        // Event loop (keyboard, mouse ...
        while (window.pollEvent(event))
        {
            // Close the window if a key is pressed or if requested
            if (event.type == sf::Event::Closed) window.close();

            // Exit the app when a key is pressed
            if (event.type == sf::Event::KeyPressed) window.close();
        }

        // Set the others parameters who need to be updated every frames (time and mouse)
        shader.setParameter("time", clk.getElapsedTime().asSeconds());
        sf::Vector2i mousePos = sf::Mouse::getPosition(window);
        shader.setParameter("mouse", sf::Vector2f(mousePos.x, mousePos.y - WINDOW_HEIGHT/2));

        // Draw the sprite with the shader on it
        window.clear();
        window.draw(spr, &shader);
        window.display();
    }

    return 0;
}

Download from Git

Files, sharders and source codes can be downloaded for GitLab : https://gitlab.com/philippe.lucidarme/sfml_tutorial/tree/master/part_005

<- Back to SFML tutorial main menu

SFML: moving a sprite with the keyboard

This article is part of a tutorial dedicated to SFML. The reader may consult the other parts of the tutorial by following this link : SFML tutorial.

This example shows how to display a sprite in fullscreen mode. The sprite can be moved with the keyboard arrow keys.

/*!
 * \file    main.cpp
 * \brief   move a sprite with the keyboard (https://www.lucidarme.me/?p=6127)
 * \author  Philippe Lucidarme
 * \version 1.0
 * \date    12/18/2016
 */

// SFML libraries
#include 
#include 
#include 

// Sprite speed (high values = high speed)
#define         SPRITE_SPEED        5

int main()
{
    // _____________________
    // ::: Create window :::

    // Create a window with the same pixel depth as the desktop
    sf::VideoMode desktopMode = sf::VideoMode::getDesktopMode();

    sf::RenderWindow window(sf::VideoMode(  desktopMode.width,
                                            desktopMode.height,
                                            desktopMode.bitsPerPixel),
                            "SFML part 3",
                            sf::Style::Fullscreen);

    // Enable vertical sync. (vsync)
    window.setVerticalSyncEnabled (true);
    // When a key is pressed, sf::Event::KeyPressed will be true only once
    window.setKeyRepeatEnabled(false);


    // ____________________
    // ::: Load texture :::

    // Create texture from PNG file
    sf::Texture texture;
    if (!texture.loadFromFile("../../img/sfml-icon-small.png"))
    {
        std::cerr << "Error while loading texture" << std::endl;
        return -1;
    }
    // Enable the smooth filter. The texture appears smoother so that pixels are less noticeable.
    texture.setSmooth(true);



    // _______________________________________
    // ::: Create sprite and apply texture :::

    // Create the sprite and apply the texture
    sf::Sprite sprite;
    sprite.setTexture(texture);
    sf::FloatRect spriteSize=sprite.getGlobalBounds();
    sprite.setOrigin(spriteSize.width/2.,spriteSize.height/2.);


        // _________________
    // ::: Main loop :::

    // Sprite coordinates
    int x=window.getSize().x/2.;
    int y=window.getSize().y/2.;
    
    // Flags for key pressed
    bool upFlag=false;
    bool downFlag=false;
    bool leftFlag=false;
    bool rightFlag=false;

    sf::Clock timer;
    while (window.isOpen())
    {
        // Process events
        sf::Event event;
        while (window.pollEvent(event))
        {
            // Close the window if a key is pressed or if requested
            if (event.type == sf::Event::Closed) window.close();

            // If a key is pressed
            if (event.type == sf::Event::KeyPressed)
            {
                switch (event.key.code)
                {
                // If escape is pressed, close the application
                case  sf::Keyboard::Escape : window.close(); break;

                // Process the up, down, left and right keys
                case sf::Keyboard::Up :     upFlag=true; break;
                case sf::Keyboard::Down:    downFlag=true; break;
                case sf::Keyboard::Left:    leftFlag=true; break;
                case sf::Keyboard::Right:   rightFlag=true; break;
                default : break;
                }
            }

            // If a key is released
            if (event.type == sf::Event::KeyReleased)
            {
                switch (event.key.code)
                {
                // Process the up, down, left and right keys
                case sf::Keyboard::Up :     upFlag=false; break;
                case sf::Keyboard::Down:    downFlag=false; break;
                case sf::Keyboard::Left:    leftFlag=false; break;
                case sf::Keyboard::Right:   rightFlag=false; break;
                default : break;
                }
            }
        }

        // Update coordinates
        if (leftFlag) x-=SPRITE_SPEED;
        if (rightFlag) x+=SPRITE_SPEED;
        if (upFlag) y-=SPRITE_SPEED;
        if (downFlag) y+=SPRITE_SPEED;

        // Check screen boundaries
        if (x<0) x=0;
        if (x>(int)window.getSize().x) x=window.getSize().x;
        if (y<0) y=0;
        if (y>(int)window.getSize().y) y=window.getSize().y;

        // Clear the window and apply grey background
        window.clear( sf::Color(127,127,127));

        // Rotate and draw the sprite
        sprite.setPosition(x,y);
        sprite.setRotation( timer.getElapsedTime().asSeconds() / M_PI * 90.f );
        window.draw(sprite);

        // Update display and wait for vsync
        window.display();
    }
    return 0;
}

Download from Git

Files and source codes can be downloaded for GitLab : https://gitlab.com/philippe.lucidarme/sfml_tutorial/tree/master/part_004

<- Back to SFML tutorial main menu

SFML: display a sprite

This article is part of a tutorial dedicated to SFML. The reader may consult the other parts of the tutorial by following this link : SFML tutorial.

This example shows how to display a sprite in fullscreen mode.

/*!
 * \file    main.cpp
 * \brief   start SFML in full screen and display a sprite (https://www.lucidarme.me/?p=6127)
 * \author  Philippe Lucidarme
 * \version 1.0
 * \date    12/18/2016
 */

// SFML libraries
#include 
#include 

int main()
{
    // _____________________
    // ::: Create window :::

    // Create a window with the same pixel depth as the desktop
    sf::VideoMode desktopMode = sf::VideoMode::getDesktopMode();

    sf::RenderWindow window(sf::VideoMode(  desktopMode.width,
                                            desktopMode.height,
                                            desktopMode.bitsPerPixel),
                            "SFML part 3",
                            sf::Style::Fullscreen);

    // Enable vertical sync. (vsync)
    window.setVerticalSyncEnabled (true);


    // ____________________
    // ::: Load texture :::

    // Create texture from PNG file
    sf::Texture texture;
    if (!texture.loadFromFile("../../img/sfml-icon-small.png"))
    {
        std::cerr << "Error while loading texture" << std::endl;
        return -1;
    }
    // Enable the smooth filter. The texture appears smoother so that pixels are less noticeable.
    texture.setSmooth(true);



    // _______________________________________
    // ::: Create sprite and apply texture :::

    // Create the sprite and apply the texture
    sf::Sprite sprite;
    sprite.setTexture(texture);
    sf::FloatRect spriteSize=sprite.getGlobalBounds();
    sprite.setOrigin(spriteSize.width/2.,spriteSize.height/2.);


    // _________________
    // ::: Main loop :::

    sf::Clock timer;
    while (window.isOpen())
    {
        // Display fps
        std::cout << int(1./timer.restart().asSeconds()) << " fps" << std::endl;

        // Process events
        sf::Event event;
        while (window.pollEvent(event))
        {
            // Close the window if a key is pressed or if requested
            if (event.type == sf::Event::Closed) window.close();
            if (event.type == sf::Event::KeyPressed) window.close();
        }

        // Clear the window and apply grey background
        window.clear( sf::Color(127,127,127));

        // Draw the sprite in the middle of the screen
        sprite.setPosition(window.getSize().x/2., window.getSize().y/2.);
        window.draw(sprite);

        // Update display and wait for vsync
        window.display();
    }
    return 0;
}

Download from Git

Files and source codes can be downloaded for GitLab : https://gitlab.com/philippe.lucidarme/sfml_tutorial/tree/master/part_003

<- Back to SFML tutorial main menu

SFML : get display resolution

This article is part of a tutorial dedicated to SFML. The reader may consult the other parts of the tutorial by following this link : SFML tutorial.

This example shows how to get available screen resolutions for full screen display:

/*!
 * \file    main.cpp
 * \brief   Display the list of available video mode (https://www.lucidarme.me/?p=6127)
 * \author  Philippe Lucidarme
 * \version 1.0
 * \date    12/18/2016
 */

// SFML libraries
#include 
#include 

int main()
{

    // Display the list of all the video modes available for fullscreen
    std::vector modes = sf::VideoMode::getFullscreenModes();

    // Display each mode
    for (std::size_t i = 0; i < modes.size(); ++i)
    {
        sf::VideoMode mode = modes[i];
        std::cout << "Mode #" << i << "\t"
                  << mode.width << "x" << mode.height << " \t "
                  << mode.bitsPerPixel << " bpp" << std::endl;
    }

    // Get and display desktop mode
    sf::VideoMode mode = sf::VideoMode::getDesktopMode();
    std::cout << "Desktop"  << "\t"
              << mode.width << "x" << mode.height << " \t "
              << mode.bitsPerPixel << " bpp" << std::endl;

    // End of application
    return 0;
}

Download from Git

Files and source codes can be downloaded for GitLab : https://gitlab.com/philippe.lucidarme/sfml_tutorial/tree/master/part_002

<- Back to SFML tutorial main menu

SFML: first program

This article is part of a tutorial dedicated to SFML. The reader may consult the other parts of the tutorial by following this link : SFML tutorial.

Packages

Install the following packages :

sudo apt-get install qtcreator qt-sdk libsfml-dev

Configure Qt

To link your application with the SFML libraries, add the following lines in the .pro file :

LIBS += -lsfml-audio
LIBS += -lsfml-graphics
LIBS += -lsfml-network
LIBS += -lsfml-window
LIBS += -lsfml-system

To avoid problem with directories, uncheck “Shadow build” in the project:

In the same way, you can uncheck “Run in terminal” :

First program

/*!
 * \file    main.cpp
 * \brief   First example of SFML (https://www.lucidarme.me/?p=6127)
 * \author  Philippe Lucidarme (from official SFML tutorial)
 * \version 1.0
 * \date    12/18/2016
 */

// SFML libraries
#include 

int main()
{
    
    // Create a new 200x200 pixels window with a title
    sf::RenderWindow window(sf::VideoMode(200, 200), "SFML tutorial : part 1");
    
    // Create a green circle with a radius of 100. pixels
    sf::CircleShape shape(100.f);
    shape.setFillColor(sf::Color::Green);
    
    
    // Main loop, while the window is open
    while (window.isOpen())
    {
        // Event loop
        sf::Event event;
        while (window.pollEvent(event))
        {
            // If close is requested by user, close the window
            if (event.type == sf::Event::Closed) window.close();
        }
        
        // Display sequence : clear screen, draw circle and update display
        window.clear();
        window.draw(shape);
        window.display();
    }
    
    // End of application
    return 0;
}

This should display the following window:

Download from Git

Files and source codes can be downloaded for GitLab : https://gitlab.com/philippe.lucidarme/sfml_tutorial/tree/master/part_001

<- Back to SFML tutorial main menu

SFML tutorial

This tutorial has been done with the following versions of software :

  • XUbuntu 16.04 LTS
  • SFML 2.3.2
  • Qt Creator 3.5.1

This tutorial is dedicated to developers who already have strong skill in C/C++. Files and source codes can be downloaded from GitLab. It is a series of commented examples, each one is associated to a topic.

Optimization : function minimization example with Matlab

This is an example of function minimization with the Matlab function fminsearch.

optim

%% Optimization example
% This file is the main script
% Written by Philippe Lucidarme
% https://www.lucidarme.me
close all;
clear all;
clc;



%% Display the function fct

figure(1);
X=[-4:0.1:4]; %% The X-axis goes from the value of -5 to +5 with a step of 0.1 (100 points)
Y=[-4:0.1:4]; %% like the X-axis
[wx,wy]=meshgrid(X,Y); %% see [MATLAB documentation][1]
% Compute each point of the mesh
for i=1:size(X,2)
    for j=1:size(Y,2)
        %Z=100.*(wy - wx.^2).^2 + (1 - wx).^2;
        Z(j,i)=fct([X(i),Y(j)]);
    end
end
% Display curb
fig=surf(wx,wy,Z); %% make a surface plot with lighting
shading interp; %% optional, try to remove it.
%     hsv        - Hue-saturation-value color map.
%     hot        - Black-red-yellow-white color map.
%     gray       - Linear gray-scale color map.
%     bone       - Gray-scale with tinge of blue color map.
%     copper     - Linear copper-tone color map.
%     pink       - Pastel shades of pink color map.
%     white      - All white color map.
%     flag       - Alternating red, white, blue, and black color map.
%     lines      - Color map with the line colors.
%     colorcube  - Enhanced color-cube color map.
%     vga        - Windows colormap for 16 colors.
%     jet        - Variant of HSV.
%     prism      - Prism color map.
%     cool       - Shades of cyan and magenta color map.
%     autumn     - Shades of red and yellow color map.
%     spring     - Shades of magenta and yellow color map.
%     winter     - Shades of blue and green color map.
%     summer     - Shades of green and yellow color map.      
colormap cool; %% here you decide the colormap: hot is the one going from white to red
view(45,65);
rotate3d;
hold on;
xlabel ('x');
ylabel ('y');
title ('Optimization');




%% Optimization

% Initial point for optimization
x0 = [0,0];

% Set parameters
% optimplotfval, display the function evaluation
% iter, display algorithm status a each interation
% Call outfun at each iteration (for display)
options = optimset('PlotFcns',@optimplotfval,'Display','iter','OutputFcn', @outfun);
% Optimization algorithm
[x,FVAL,EXITFLAG,OUTPUT] = fminsearch(@fct,x0,options);


%% Display results

FVAL
OUTPUT
x
figure(1);
plot3 (x(1),x(2),fct(x),'or','MarkerSize',10,'LineWidth',5);
function y = fct( x )
% fct  function to minimize
%   x = [x,y] input vector
%   y = function output (scalar)
% Written by Philippe Lucidarme
% https://www.lucidarme.me

% Rosenbrock's function
%y = 100*(x(2) - x(1)^2)^2 + (1 - x(1))^2;

%y = (x(1)-4).^2 .* (x(2)-1.2).^2;

y = sinc(x(1)).*sinc(0.3*x(2));

end
function stop = outfun(x, optimValues, state)
% fct  this function is called at each step of the optimization process
%   x :             the point computed by the algorithm at the current iteration.
%   optimValues :   is a structure containing data from the current iteration.
%   state :         current state of the algorithm.
% Written by Philippe Lucidarme
% https://www.lucidarme.me

figure (1);
plot3 (x(1),x(2),optimValues.fval,'.k','MarkerSize',10);
stop=false;

Installing FEBFMT1030 drivers on Linux

This post explain how to install drivers for the FEBFMT1030 evaluation board. This installation has been done with the following versions of sofware :

  • XUbuntu 14.04 LTS

Software can be downloaded from this page : https://www.fairchildsemi.com/product-technology/mems-module/ or her :

First, install the dependencies :

sudo apt-get install realpath sharutils liblapack3 build-essential

Extract the archive, and extract the Linux folder. Start a terminal (ctrl-alt-t) and move to the archive :

 cd path/to/the/archive 

Get acces to the USB devices

Add yourself to the dialout group :

sudo usermod -G dialout -a $USER

After adding yourself to the group, either relogin to your user, or call:

newgrp dialout

Install SDK

Make the scripts executable :

chmod +x *.sh

Run the scripts :

 
sudo ./mtsdk_linux_4.4.135.sh
sudo ./mfmsdk_linux_4.4.135.sh
sudo ./fcs_mfmsdk_linux_4.4.135.sh
sudo ./fcs_mtsdk_linux_4.4.135.sh 

Install MTManager

Extract the archive fcs_mtmanager_Release-Linux-x64_135.tar.gz, move to the linux-64/bin directory. Start the manager :

./mtmanager

Support for the Development Board is present in recent kernels (since June 12, 2015). If your kernel does not support the Board, you can add this manually

sudo /sbin/modprobe ftdi_sio
echo 2639 0300 | sudo tee /sys/bus/usb-serial/drivers/ftdi_sio/new_id

If the board is recognized, but you cannot ever access the device, check the troubleshooting section in /usr/local/fairchild/README.MTSDK

Compile your first program

Add the libraries to the dynamic linker :

sudo ldconfig /usr/local/fairchild
sudo ldconfig /usr/local/xsens

Move to the example directory :

cd /usr/local/fairchild/examples/mtsdk/

Compile :

make

Move to the build directory :

cd src_cpp

Launch the app :

./example

The device is natively located in /dev/ttyUSB0, and baud rate is 115200.

Allowed characters in filename

What are the allowed and forbidden character in file name ? The POSIX “Fully portable filenames” lists the following characters:

  • Alphabet upper case letters : A B C … Z (not recommended, see below)
  • Alphabet lower case letters : a b c … z
  • Numbers : 0 1 2 … 9
  • Dot : .
  • Underscore : _
  • Minus :

Hyphen must not be first character (_ . -).

Example :

FileName_01-03-16.txt

Download

The app check_file_name renames all the files and folders in every sub directories.

Scroll, zoom, drag, tooltip, contextual menu and draw in an Image Widget

This post demonstrates an image widget for Qt. The class rOg_image supports the following features:

  • display a QImage in the widget
  • display a raw image in the widget
  • support smart resize
  • mouse wheel zoom in, zoom out
  • drag image with mouse
  • right button contextual menu
  • overload to draw over the image (background or foreground)
  • overload to display tool-tip over the image

Download

Acknoledgents

This class has been developed in collaboration with Simon Landrault (Eskimon).

Memory access optimization

Accessing large data stored in memory may be time consuming. As data is general stored in RAM, it requires a transfer from to the processor. This transfer is time consuming on a PC because RAM and processor are physically separated. When you want to program multiple access to data stored in RAM, the question of optimization may be an issue. I’ve read and heard many things about this topics, here is (almost) the truth. This post will focus on reading and writing data in large array. We will not consider memory allocation that is usually done only once. The following benchmarks have been performed on an Intel architecture (octo-core I7) under Ubuntu 14.04, data were stored in memory (no swap on disk).

Continuous versus Random access

The first thing I read is that continuous access to an array is faster than random access. Let’s consider the following codes:

 
// Continuous access
uint16_t* array=new uint16_t [SIZE];
uint16_t Val;
for (uint64_t i=0;i

versus

// Random reading of data
uint16_t* array=new uint16_t [SIZE];
uint16_t Val;
for (uint64_t i=0;i

The TIC and TOC macros measure the computation time. Here are the results :

test1

The first conclusion is that is is true. We may imagine that the requested byte is copied from memory to the processor. But in fact, this is not what happens. The processor always copy a segment of data, it means that during continuous access, the number of copy is limited because neighbored bytes just need one copy. In random access, a copy must be done at each access. It's not clear about why Writing is faster than Reading. If you have the answer, leave me a message.

New versus Malloc


Memory allocation can be done via new(c++) or malloc(c). The question here is not what the faster for allocating memory, the question are data access equivalent. Are data allocated with new faster compared to data allocated with malloc ? Here is the answer:

test2

Obviously, this is equivalent. This is not really a surprise, in both cases data, are stored in memory. The tiny difference is probably due to other processes that took some resources during benchmark.

Multidimensional array access

Let's take the example of a two-dimensions array dynamically allocated (for example and image). We want to access to pixel at coordinates (x,y). The first solution consists in creating an array of size width*height and accessing to the elements by computing the index y*width+x.

// Test 1 
uint16_t* array=new uint16_t [SIZE];
// ...
TIC_MACRO;
Val=array[y*WIDTH+x];
TOC_MACRO;

Of course, this first solution requires the computation of a product and an addition that may be time consuming. A solution frequently proposed is to create a second array of pointers containing the address of each row. This solution requires another array, but don't need any calculation:

// Test 2
uint16_t* array=new uint16_t [SIZE];
uint16_t** pArray=new uint16_t* [HEIGHT];
for (int i=0;i

If the data don't have to be stored in a continuous way, it is even possible to allocate each row of the main array separately:

// Test 3
uint16_t** pArray=new uint16_t* [HEIGHT];
for (int i=0;i

Here are the results:
test3

As you can see, the first solution is the fastest, event if there is a calculation. On modern computers, calculation requires in fact few cycles while large memory access is still an issue. The second solution requires two memory accesses, one for getting the address of row, and the second for the data. The third solution is still worth because it requires more transfers from memory to the processor since data are scattered in memory.

Data types

Of course, choosing the right type of data may optimize memory, but the last question is : does the type of data is important for fast computing ? I have heard that if data are aligned on 32 or 64 bits it may increase the speed because computers are optimized for this format of data. For example, an a 32 bits processor, accessing an array of char is slower than accessing an array of int. I performed read/write operations on several types of data. Here are the results:

test4

Clearly, the type of data changes the time of access. The larger are the data is, the slower is the access. I guess this is because big data generally requires more copies from memory to processor due to the fact that an array of uint64_t is 8 times larger than the same array of uint8_t. This result must be consider with precaution because it is not necessary true when accessing few bytes.

Download

GIT reminder

Git global setup

Set user name :

git config --global user.name "Firstname Lastname"

Set user email :

git config --global user.email "[email protected]"

Create a new repository

git clone 
cd repo_folder
touch README.md
git add README.md
git commit -m "add README"
git push -u origin master

Existing folder or Git repository

cd existing_folder
git init
git remote add origin 
git add .
git commit
git push -u origin master

Commit, pull and push

Update local version of the code :

git pull

Update code on repository :

git commit -a -m "Add a comment here"
git push origin master

Delete a file:

git rm filename

Discard local changes and get repository last version:

git checkout -- .

View list of servers

git remote -v

Create a new branch

git branch brancheName

Create a new branch from a previous commit

git branch brancheName commitName

List branch

git branch

Change branch

git checkout branchName

Create a new branch and switch to

git checkout -b branchName [commitName]

Merge current branch with master

git merge branchName

Push current branch to the server

git push origin branchName

Delete a branch

git branch -d branchName

Force to delete a branch

git branch -D branchName

Get last changes from master to the current branch

git pull master

or

git rebase

Commit one file

git add fileName
git commit -a -m "Comment"

OpenGL and Qt-Creator

This post is a simple example of an OpenGL widget display in a Qt window. This example has been programmed with the following software versions:

  • Xubuntu 14.04 LTS
  • Qt Creator 3.0.1
  • Qt 5.2.1 (GCC 4.8.2, 64 bit)

Screenshot

This application display a 3-axis frame and a cube made of points:
capture

Software installation


You may need to install the OpenGL Utility Toolkit (GLUT):

sudo apt-get install freeglut3 freeglut3-dev

Download