SFML community forums

Help => Graphics => Topic started by: m3tr on November 13, 2018, 04:19:51 pm

Title: Mismatch in coordinate system of window and getPixel
Post by: m3tr on November 13, 2018, 04:19:51 pm
#include <SFML/Graphics.hpp>
#include <iostream>
int main()
{
    sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!",sf::Style::Default);
    window.setVerticalSyncEnabled(true);
    sf::Vertex point;
    point.color = sf::Color::Red;
    point.position = sf::Vector2f(2,2);
    window.draw(&point,1,sf::Points),
    window.clear();
    window.display();
    sf::Image img = window.capture();
    window.display();
    window.clear();
    window.draw(&point,1,sf::Points);
    img = window.capture();
    std::cout << img.getPixel(2,1).toInteger() <<  '\n'; // gives red
    std::cout << img.getPixel(2,2).toInteger() <<  '\n'; //gives black, this should have given red
    window.close();
    return 0;
}
 
Pixel (2,2) is red using draw but is black using getPixel. Why?
Title: Re: Mismatch in coordinate system of window and getPixel
Post by: Laurent on November 13, 2018, 04:23:23 pm
Typical mistake ;)

Use (2.5, 2.5) as your vertex coordinates; this is the center of a pixel so you're sure it will be the right one. (2, 2), on the other hand, is at the intersection of 4 pixels and OpenGL has to choose one of them when it rasterizes your point primitive -- and it may not be the one you expect.
Title: Re: Mismatch in coordinate system of window and getPixel
Post by: m3tr on November 13, 2018, 05:28:52 pm
It worked.
But why pixel/point coordinates are not integers?

PS: Is this the best way to solve this problem?
Title: Re: Mismatch in coordinate system of window and getPixel
Post by: Laurent on November 13, 2018, 07:28:11 pm
Vertex coordinates are real numbers. A pixel spans from coordinates (x, y) to coordinate (x + 1, y + 1). So (x, y) is actually its corner, as well as the corner of 3 other pixels. So, when you draw points, you must use center coordinates, ie. + 0.5. That's not a workaround, that's how things work.

Images on the other hand, use integer coordinates, where (x, y) is exactly one pixel, the one at row y and column x.