Created
July 19, 2014 15:38
-
-
Save Mischa-Alff/67491f0adbe510b30a2d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <memory> | |
#include <SFML/Graphics.hpp> | |
int main() | |
{ | |
sf::RenderWindow window{{800, 600}, "Backface Calculations for zsbzsb"}; | |
sf::CircleShape light_point(5.f); | |
light_point.setOrigin({5.f, 5.f}); | |
light_point.setPosition(static_cast<sf::Vector2f>(window.getSize())/2.f); | |
sf::CircleShape* circle_octogon = new sf::CircleShape(50.f, 8); | |
sf::VertexArray octogon(sf::TrianglesFan, 8); | |
for(int i{0}; i<circle_octogon->getPointCount(); ++i) | |
{ | |
octogon[i] = sf::Vertex(circle_octogon->getPoint(i), sf::Color::Green); | |
} | |
delete circle_octogon; | |
auto default_octogon = octogon; | |
sf::VertexArray lines(sf::Lines, 4); | |
while(window.isOpen()) | |
{ | |
sf::Event event; | |
while(window.pollEvent(event)) | |
{ | |
switch(event.type) | |
{ | |
case sf::Event::Closed: | |
window.close(); | |
} | |
} | |
auto mouse_pos = static_cast<sf::Vector2f>(sf::Mouse::getPosition(window)); | |
// Generate lines | |
{ | |
auto light_pos = light_point.getPosition(); | |
auto vec_perp = mouse_pos-light_pos; | |
std::swap(vec_perp.x, vec_perp.y); | |
vec_perp.x = -vec_perp.x; | |
lines[0] = sf::Vertex( vec_perp+mouse_pos, sf::Color::Blue); | |
lines[1] = sf::Vertex(-vec_perp+mouse_pos, sf::Color::Blue); | |
lines[2] = sf::Vertex( light_pos, sf::Color::Red); | |
lines[3] = sf::Vertex( mouse_pos, sf::Color::Red); | |
} | |
// Calculate backface vectors | |
{ | |
for(int i{0}; i < default_octogon.getVertexCount(); ++i) | |
{ | |
//Reset shape | |
octogon[i] = default_octogon[i]; | |
//Translate shape | |
octogon[i].position += mouse_pos - sf::Vector2f{50.f, 50.f}; | |
//lines[0] and lines[1] are our perpendicular line | |
//Get the side of the vertex | |
bool side = std::signbit( | |
(lines[1].position.x-lines[0].position.x)*(octogon[i].position.y-lines[0].position.y) | |
- | |
(lines[1].position.y-lines[0].position.y)*(octogon[i].position.x-lines[0].position.x) | |
); | |
// If side is the same, set backface vector to red | |
if(side == std::signbit(mouse_pos.x)) | |
octogon[i].color = sf::Color::Red; | |
} | |
} | |
window.clear(); | |
window.draw(octogon); | |
window.draw(light_point); | |
window.draw(lines); | |
window.display(); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment