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

Author Topic: Mismatch in coordinate system of window and getPixel  (Read 1940 times)

0 Members and 1 Guest are viewing this topic.

m3tr

  • Newbie
  • *
  • Posts: 2
    • View Profile
Mismatch in coordinate system of window and getPixel
« 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?

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32498
    • View Profile
    • SFML's website
    • Email
Re: Mismatch in coordinate system of window and getPixel
« Reply #1 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.
Laurent Gomila - SFML developer

m3tr

  • Newbie
  • *
  • Posts: 2
    • View Profile
Re: Mismatch in coordinate system of window and getPixel
« Reply #2 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?

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32498
    • View Profile
    • SFML's website
    • Email
Re: Mismatch in coordinate system of window and getPixel
« Reply #3 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.
« Last Edit: November 30, 2018, 07:50:33 am by Laurent »
Laurent Gomila - SFML developer

 

anything