Welcome, Guest. Please login or register. Did you miss your activation email?

Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.

Topics - Foaly

Pages: 1 [2] 3 4
Audio / Confusing error message in sf::SoundBuffer
« on: September 26, 2013, 09:27:02 pm »
While I was working on the implementation of the capture device selection I noticed something that's a little weird. If you try to save an empty sf::SoundBuffer you'll get a confusion error message.
When you run this code:
#include <SFML\Audio.cpp>

int main()
    sf::SoundBuffer buffer;
You will get this console output: Failed to create sound file "example.wav" (Format not recogized)
I tryed different formats (.wav, .ogg, ...) but they all failed. If there are sampled in the buffer the program runs as expected.
I fired up my debugger and saw that the error message is caused by the failure of sf_open() in sf::SoundFile::openWrite(). I checked the format that is passed to sf_open (fileInfos struct) and it matches the one for signed 16-bit WAV. I also noticed that channels and sampleRate are set to 0. So what I'm thinking is that sf_open fails with the error message "Format not recognized" eventhough the format is correct, but when the channel count and the sample rate is still at zero.

Wouldn't it be a good idea to check if the buffer contains samples before saving it? That way there could be a more discribtiv error message (i.e. "Nothing to record").

Audio / Help with the design for selecting audio capture device
« on: September 19, 2013, 11:35:45 am »
Hello everybody!
In an effort to make the requested community driven development happen (on a small scale ;)) and also extend SFMLs multimedia functionality (but also for me personally to learn what I could have done better) I would like to invite everybody to start a discussion here with the goal to find a good design for the selection of the audio capture device.
Yesterday I proposed a "design" on GitHub. It was more or less the code I was using and now I would like to make sure that the design holds up to the standarts of SFML. So I would like to welcome everybody to rip it apart and put it back together in a better way!
Instead of endless commits changing little things and littering the pull request, I would like to find a solid design here and then hand it over to Laurent to review it.
Laurent already mentioned in the pull request that maybe the selection of the audio capture device should be something that is only possible on initialization. I only agree partially. This is something that you should also be able to set in the initilization step. But I don't see a reason why you shouldn't be able to change it while recording. I tested it with two mics and there is no noticable gap in the samples.
But like I said I would like to hear everybody's input on this.
So please everybody come and help.
And now fire away!

Feature requests / Modulo for sf::Time
« on: July 17, 2013, 12:55:48 am »
I wanted to do a modulo operation on a sf::Time object today and I was suprised there isn't one. Is there a specific reason for that? There is an overload for basicaly every other operation. Could it be added?
A use case would be something like this:
currentTime += deltaTime;
if(currentTime > duration)
    currentTime = sf::microseconds(currentTime.asMicroseconds() % duration.asMicroseconds());
would be shortend to this
currentTime = currentTime % duration;
// or even shorter
currentTime %= duration;

Graphics / Fix for issue #243
« on: February 13, 2013, 10:43:03 pm »
There is an issue on the tracker, which I was interested in for a long time. I finally found some time to investigate it and noticed it is very easy to implement. Basically in the same spots a line for the underline style is drawn, I check for the strike through style and draw a line. That's pretty much it. I tested the results with different font and it works as expected. The patch doesn't break the current API.
Also in your comment next to the italic variable you say 12 degree, but 2 * pi * (12/360) is 0.2094... instead of 0.208. I "fixed" that (it's not like anybody is gonna notice it, just for the mathematical correctness).
I don't really know how to apply the patch to github and I thought I should get some feedback first anyway. So I'm just gonna present the patch file here.
--- C:\Librarys\SFML Source\SFML\src\SFML\Graphics\Text.cpp     Thu Jan  3 12:39:24 2013
+++ C:\Users\User\Programs\Strikethrough Text\Text.cpp  Wed Feb 13 21:12:38 2013
@@ -238,11 +238,13 @@
     // Compute values related to the text style
-    bool  bold               = (m_style & Bold) != 0;
-    bool  underlined         = (m_style & Underlined) != 0;
-    float italic             = (m_style & Italic) ? 0.208f : 0.f; // 12 degrees
-    float underlineOffset    = m_characterSize * 0.1f;
-    float underlineThickness = m_characterSize * (bold ? 0.1f : 0.07f);
+    bool  bold                = (m_style & Bold) != 0;
+    bool  underlined          = (m_style & Underlined) != 0;
+    bool  strikethrough       = (m_style & Strikethrough) != 0;
+    float italic              = (m_style & Italic) ? 0.209f : 0.f; // 12 degrees
+    float lineThickness       = m_characterSize * (bold ? 0.1f : 0.07f);
+    float underlineOffset     = m_characterSize * 0.1f;
+    float strikethroughOffset = m_characterSize * 0.4f ;
     // Precompute the variables needed by the algorithm
     float hspace = static_cast<float>(m_font->getGlyph(L' ', m_characterSize, bold).advance);
@@ -260,24 +262,40 @@
         x += static_cast<float>(m_font->getKerning(prevChar, curChar, m_characterSize));
         prevChar = curChar;
-        // If we're using the underlined style and there's a new line, draw a line
-        if (underlined && (curChar == L'\n'))
-        {
-            float top = y + underlineOffset;
-            float bottom = top + underlineThickness;
-            m_vertices.append(Vertex(Vector2f(0, top),    m_color, Vector2f(1, 1)));
-            m_vertices.append(Vertex(Vector2f(x, top),    m_color, Vector2f(1, 1)));
-            m_vertices.append(Vertex(Vector2f(x, bottom), m_color, Vector2f(1, 1)));
-            m_vertices.append(Vertex(Vector2f(0, bottom), m_color, Vector2f(1, 1)));
-        }
         // Handle special characters
         switch (curChar)
-            case L' ' :  x += hspace;        continue;
-            case L'\t' : x += hspace * 4;    continue;
-            case L'\n' : y += vspace; x = 0; continue;
+            case L' '  : x += hspace;     continue;
+            case L'\t' : x += hspace * 4; continue;
+            case L'\n' :
+                // If we're using the underlined style and there's a new line, draw a line
+                if(underlined)
+                {
+                    float top = y + underlineOffset;
+                    float bottom = top + lineThickness;
+                    m_vertices.append(Vertex(sf::Vector2f(0, top),    m_color, Vector2f(1, 1)));
+                    m_vertices.append(Vertex(sf::Vector2f(x, top),    m_color, Vector2f(1, 1)));
+                    m_vertices.append(Vertex(sf::Vector2f(x, bottom), m_color, Vector2f(1, 1)));
+                    m_vertices.append(Vertex(sf::Vector2f(0, bottom), m_color, Vector2f(1, 1)));
+                }
+                // If we're using the strikethrough style and there's a new line, draw a line across all charcters
+                if (strikethrough)
+                {
+                    float top = y - strikethroughOffset;
+                    float bottom = top + lineThickness;
+                    m_vertices.append(Vertex(sf::Vector2f(0, top),    m_color, Vector2f(1, 1)));
+                    m_vertices.append(Vertex(sf::Vector2f(x, top),    m_color, Vector2f(1, 1)));
+                    m_vertices.append(Vertex(sf::Vector2f(x, bottom), m_color, Vector2f(1, 1)));
+                    m_vertices.append(Vertex(sf::Vector2f(0, bottom), m_color, Vector2f(1, 1)));
+                }
+                y += vspace;
+                x = 0;
+                continue;
             case L'\v' : y += vspace * 4;    continue;
@@ -308,7 +326,19 @@
     if (underlined)
         float top = y + underlineOffset;
-        float bottom = top + underlineThickness;
+        float bottom = top + lineThickness;
+        m_vertices.append(Vertex(sf::Vector2f(0, top),    m_color, Vector2f(1, 1)));
+        m_vertices.append(Vertex(sf::Vector2f(x, top),    m_color, Vector2f(1, 1)));
+        m_vertices.append(Vertex(sf::Vector2f(x, bottom), m_color, Vector2f(1, 1)));
+        m_vertices.append(Vertex(sf::Vector2f(0, bottom), m_color, Vector2f(1, 1)));
+    }
+    // If we're using the strikethrough style, add the a line across all charcters
+    if (strikethrough)
+    {
+        float top = y - strikethroughOffset;
+        float bottom = top + lineThickness;
         m_vertices.append(Vertex(Vector2f(0, top),    m_color, Vector2f(1, 1)));
         m_vertices.append(Vertex(Vector2f(x, top),    m_color, Vector2f(1, 1)));
For the header file it's simply a matter of adding Strikethrough = 1 << 3 ///< Strikedthough characters to the enum.
If I should post this somewhere else, please tell me.

Graphics / sf::RenderTexture repeated
« on: January 31, 2013, 04:16:33 pm »
I was working with sf::RenderTextures yesterday and I noticed that they don't have a setRepeat() method. Is this a bug or is there a reason why it's left out?

System / Tiny Correction to the source
« on: January 29, 2013, 09:15:38 pm »
The other day I was reading thought the source a bit and I was looking at the win32 clock implementation. I noticed a tiny tiny thing there. It's a white space indentation error in line 54 there is a tab character instead of 4 white spaces. It's not even worth creating a thread, but I thought I'd point it out anyway.

Also all the files start Copyright (C) 2007-2012 Laurent Gomila. I think we can safely move to 2013 now :D

Graphics / sf::RenderTexture swapping problem
« on: January 28, 2013, 11:46:55 pm »
This thread is for the problem when swapping between two or more sf::RenderTextures described here: http://en.sfml-dev.org/forums/index.php?topic=10328.msg71160#msg71160
I just wanted to keep it separate, so the other thread can go back to it's original topic.  So we can discus things here, when Laurent is back.

Graphics / texture.update() crash
« on: January 23, 2013, 10:08:05 pm »
Hi there!
I am trying to fill a texture with some gray color. My very simple test code crashes... The code:
#include <SFML/Graphics.hpp>

int main()
    sf::RenderWindow window(sf::VideoMode(500, 500), "SFML works!");

    sf::Uint8 pixelBuffer [250000];

    sf::Texture texture;
    texture.create(500, 500);

    while (window.isOpen())
        sf::Event event;
        while (window.pollEvent(event))
            if(event.type == sf::Event::Closed)

            if(event.type == sf::Event::KeyReleased && event.key.code == sf::Keyboard::Escape)


        for(int i = 0; i < 249999; i++)
            sf::Uint8 color = 128;
            pixelBuffer[i] = (color << 16) | (color << 8) | color;
        texture.update(pixelBuffer, 500, 500, 0, 0);  //<---- crash happens here


    return 0;
I get a SIGSEGV fault. I haven't used the update() method of sf::Texture before, so I don't really know if I handle everything correct. Does somebody know what I'm doing wrong? I'm using the latest source with MinGW 4.7.2 on windows 7.
Thanks, Foaly

Graphics / 2D Water
« on: January 18, 2013, 02:42:23 pm »
I know that this forum is not for general programming issues, but for SFML specific stuff. I'm stuck with a problem that I can't solve and I'm not sure if it's something general I'm doing wrong or if it's something SFML specific I'm doing wrong, so I just thought I ask :)
I am trying to implement the 2D water effect described here: http://freespace.virgin.net/hugo.elias/graphics/x_water.htm
I want to implement it using shaders and rendertextures, because it seems more efficient to me, than using arrays of pixels and then upload those to the GPU each frame. Right now I trying to implement the creation of the Heightmap.
Here is what I'm doing: I have 3 rendertextures (3 because you can't read and write to a rendertexture at the same time) firstBuffer contains the Heightmap 2 frames ago, secondBuffer contains the heightmap form the last frame and finalBuffer is where the heightmap is drawn to. Releasing space puts a new "ripple" at the mouse position.
Here is my code:
#include <SFML/Graphics.hpp>
#include <iostream>

int main()
    sf::RenderWindow window(sf::VideoMode(600, 600), "SFML works!");

    sf::RenderTexture buffers[3];
    buffers[0].create(500, 500);
    buffers[1].create(500, 500);
    buffers[2].create(500, 500);
    sf::RenderTexture* firstBuffer = buffers;
    sf::RenderTexture* secondBuffer = &buffers[1];
    sf::RenderTexture* finalBuffer = &buffers[2];

    sf::Shader waterHeightmapShader;
    waterHeightmapShader.loadFromFile("waterHeightmapShader.glsl", sf::Shader::Fragment);

    sf::Sprite sprite;
    sprite.setPosition(50, 50);

    while (window.isOpen())
        waterHeightmapShader.setParameter("mousePosition", sf::Vector2f(-1, -1));

        sf::Event event;
        while (window.pollEvent(event))
            if(event.type == sf::Event::Closed)

            if(event.type == sf::Event::KeyReleased && event.key.code == sf::Keyboard::Escape)

            // when the spacebar is pressed, add a new ripple at the mouse position
            if(event.type == sf::Event::KeyReleased && event.key.code == sf::Keyboard::Space)
                sf::Vector2i mousePosition = sf::Mouse::getPosition(window);
                if(mousePosition.x > 50 && mousePosition.y > 50 && mousePosition.x < 600 - 50 && mousePosition.y < 600 - 50)
                    // this is an ugly hack
                    mousePosition.x -= 50;
                    mousePosition.y -= 50;

                    sf::Vector2f mouse(mousePosition);

                    mouse.x /= 500.f;
                    mouse.y /= 500.f;

                    std::cout << mouse.x << " " << mouse.y << std::endl;

                    waterHeightmapShader.setParameter("mousePosition", mouse);


        waterHeightmapShader.setParameter("textureTwoFramesAgo", firstBuffer->getTexture());
        waterHeightmapShader.setParameter("textureOneFrameAgo", secondBuffer->getTexture());

        // create the heightmap
        finalBuffer->draw(sf::Sprite(secondBuffer->getTexture()), &waterHeightmapShader);



        // swap the buffers around, first becomes second, second becomes third and third becomes first
        sf::RenderTexture* swapper = firstBuffer;
        firstBuffer = secondBuffer;
        secondBuffer = finalBuffer;
        finalBuffer = swapper;

    return 0;
And the shader:
// Scene buffer
uniform sampler2D textureTwoFramesAgo;
uniform sampler2D textureOneFrameAgo;
uniform vec2 mousePosition;

const float textureSize = 500.0;
const float pixelSize = 1.0 / textureSize;

void main()
    // pixels position
    vec2 position = gl_TexCoord[0].st;

    vec4 finalColor = (texture2D(textureTwoFramesAgo, vec2(position.x - pixelSize, position.y)) +
                       texture2D(textureTwoFramesAgo, vec2(position.x + pixelSize, position.y)) +
                       texture2D(textureTwoFramesAgo, vec2(position.x, position.y + pixelSize)) +
                       texture2D(textureTwoFramesAgo, vec2(position.x, position.y - pixelSize))   ) / 2.0 -
                       texture2D(textureOneFrameAgo, position);

    // damping
//    finalColor *= 0.5;

    // add new ripples
    if(mousePosition.x > 0.0)
        if(distance(position, mousePosition) < pixelSize * 5.0)
            finalColor = vec4(1.0, 1.0, 1.0, 1.0);

    gl_FragColor = finalColor;

If you give the code a try you'll see my problem. The problem is that whenever I create a new "ripple" it appears, but the next frame it appears to be flipped around the x-axis and the frame after that the rendertexture seems to be empty... Also the circle spreads, but it doesn't do the up and down/ripple/wavy effect.
I know the explanation is shitty, but I don't know how to describe it any better. I tried to make a video of it, but my computer refuses to do so (really I tried everything)

Sorry again for abusing this forum, but there is a lot of smart people here and I thought maybe someone is able to help me or point me in the right direction.
Thanks in advance

System / sf::Time constructor
« on: January 15, 2013, 05:50:04 pm »
The other day I was writing a class that has a sf::Time as a member variable. That was when I noticed that the time class doesn't have a contructor other than the default one. That means I can't initilize it dirctly in the initialization list of my constructor. So I was wondering is there a specific reason why the time class doesn't have a constructor other than the default one? Or could there maybe be a constructor added that takes a duration in say milliseconds?

Graphics / sf::Sprite rotate(45) bug
« on: January 14, 2013, 06:58:50 pm »
While testing my AnimatedSprite class i noticed something weird. First I though it was something on my end, but after playing around a little more I noticed, that the sf::Sprite class has the same problem... (which makes sense, because I use the same code for calculating the texture coordinates)
Whenever I use the setTextureRect() member of a sprite and the left member is set to something other then the left border of the texture and I then rotate the sprite by 45 degrees the texture is offset by one pixel. Whether I use rotate or setRotation doesn't make a difference. This only happens with 45 or -45 or multiples of them (i.e.: 405, 765 etc.). This seems very weird to me, because the sf::Transform should not affect the texture coordinates, should it? It only affects the vertices, right?
Only thing I can think of, that might explain it, is that there is a float rounding error in updateTexCoords().

If the above makes no sense at all, then try this minimal example:
#include <SFML/Graphics.hpp>

int main()
    sf::RenderWindow window(sf::VideoMode(500, 500), "Rotate Test");

    sf::Texture texture;

    sf::Sprite sprite;
    sprite.setPosition(200, 200);
    sprite.setTextureRect(sf::IntRect(1, 1, 98, 98));

    sf::Event event;

            if (event.type == sf::Event::Closed)
            if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape)


    return 0;

with this image:

Rotated by 45° it looks like this:

The red boarder only appears when rotated by 45° any other angle works fine.

Can somebody else confirm this? I am using Windows 7 x64, a Geforce GTX 500 Ti, the latest source compiled with MinGW (gcc 4.7.2)

SFML wiki / Animated Sprite class
« on: January 13, 2013, 04:03:26 pm »
Hello everybody!
I wrote a class that provides an easy interface to Animations and follows the design of sf::Spite. I find it very helpful, so I though I share it with everybody! Go check it out and tell me what you think! Any input is appreciated.
Here is the link to the Wiki page.

Graphics / Wiki TileMap Question
« on: January 07, 2013, 10:37:28 pm »
Hello everybody,
I was reading though this post and I have a related queation. I want to implement a Tile Engine. I also think the best way to go is a vector of Vertices, because of the size limitation of the RenderTexture. In the thread mentioned above there is a link to a wiki page, that shows a example implementation using a vertex array. It looks good, but reading through it I was wondering one thing: Is the clipping necessary? Isn't it actually costing performance?
Because from my experience it's more efficient to draw a big Vertexarray (containing Quads) once instead of drawing a lot of quads. And if I understand the source code correct every quad inside the clipping range is drawn individually. The tile map would have to be huge in order for this to be more efficient than simply drawing the entire Vertexarray. Plus you have to execute the code for the clipping calculation every loop.
Maybe I'm missing something, but I was wondering and though maybe someone has a question for it.


edit: Another question: Why are you using a 2 dimensional Array of sf::VertexArray's instead of one std::vector<sf::Vertex>?

Audio / Trying to solve issue #203
« on: January 03, 2013, 03:13:33 pm »
I started to work on an issue that has been bugging me for quiet some time now: issue #203. The issue is, that if a music is paused or stopped and you call setPlayingOffset() on it the music gets restarted.
The problem is not as simple as it might first look. My solution to the problem was to simply get the status of the music at the beginning of the function and restore it at the end. I tryed this:

void SoundStream::setPlayingOffset(Time timeOffset)
    // Get old playing status
    Status oldStatus = getStatus();

    // Stop the stream

    // Let the derived class update the current position

    // Calculate new position
    m_samplesProcessed = static_cast<Uint64>(timeOffset.asSeconds() * m_sampleRate * m_channelCount);

    // Play
    m_isStreaming = true;

    // Restore to old status
    if(oldStatus == Stopped)
        stop();   // stop
    else if(oldStatus == Paused)
        pause();   // paused
The problem with this code is that it's correct, but it doesn't work as expected, because if the music is paused it still restarts. After some investigation i found out, this is because the pause command is executed faster than the play command in the threaded function. So the music is actually paused, but played right afterwards. If I insert a sleep(milliseconds(20)); before restoring the old state (which is obviously not an option) everything works as expected.
I also tried this:
    // Calculate new position
    m_samplesProcessed = static_cast<Uint64>(timeOffset.asSeconds() * m_sampleRate * m_channelCount);

    // Restore to old status
    if(oldStatus != Stopped)
        m_isStreaming = true;   // paused
        if(oldStatus == Playing)
            m_thread.launch();   // played
At first it seemed to work fine, but when the music was in a paused state it is not possible to resume it afterwards, because the thread is never actually launched...

So I am a little stuck now and not really sure how to continue from here. So I thought I share what I found so far and ask if somebody has another idea. Because this seems like an annoying bug, that should be fixed :D
Anyways I have a debugging environment set up and am happy to help.
Foaly :)

Graphics / Optimizing a lot of sprites
« on: November 30, 2012, 08:14:53 pm »
Hello everybody.
I have a question on optimization of sprite rendering. In my application I have an std::deque of sprites. Think of it as a particle system. Sprites are getting added, updated (positions) and deleted a lot. For rendering I simply iterate through the deque and draw them to the render target. Around 3000 sprites you can feel the framerate getting slower. Does anybody have an idea how I could optimize this? I'm not sure maybe I could use a vertexarray, but I have never worked with those, so I don't really know how... Does anybody have an idea?
Thanks in advance, Foaly

Pages: 1 [2] 3 4