user3723184
user3723184

Reputation: 60

Why does SFML Shader cause segmentation fault?

Why does sf::Shader cause segmentation fault.I am going to show the code and i am telling to those that look the code that i use an engine and it works perfectly.So it doesn't cause the crash except with sf::Shader.And the code stops when i load the shader.

main.cpp

#include <iostream>
#include "CoreEngine.h"
#include "maingame.h"

int main()
{
//CoreEngine e(new MainGame(new Vector2i(800, 600), "Mama"));
//e.start();
Window::createWindow(800, 600, "Mama");
Window::clearColor(124, 32, 125);

bool running = true;

while(running){
    if(Window::isWindowClosed())
        running = false;


sf::RectangleShape shape(sf::Vector2f(20, 20));
shape.setPosition(10, 10);
sf::Shader shader;
if(!shader.loadFromFile("fragment.fs", sf::Shader::Fragment))
    std::cout << "dfsfsdf";
    Window::clear();
    Window::getDrawer()->draw(shape, &shader);
    Window::render();
}
}

Here is a compiled version of the code.

#include <iostream>
#include <SFML/Graphics.hpp>

int main()
{
//CoreEngine e(new MainGame(new Vector2i(800, 600), "Mama"));
//e.start();
sf::RenderWindow window(sf::VideoMode(800, 600), "Msadama");

sf::Shader shader;
if(!shader.loadFromFile("fragment.fs", sf::Shader::Fragment)){
    std::cerr << "Shader failed to load" << std::endl;
    return 0;
}
sf::RectangleShape shape(sf::Vector2f(20, 20));
shape.setPosition(10, 10);
while(window.isOpen()){
   sf::Event event;

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




    window.clear();
    window.draw(shape);
    window.display();
}
}

Upvotes: 0

Views: 410

Answers (1)

TartanLlama
TartanLlama

Reputation: 65580

Your call to sf::Shader::loadFromFile is failing, which triggers your if statement because you are checking for the wrong condition. What you really want is:

sf::Shader shader;
if(!shader.loadFromFile("fragment.fs", sf::Shader::Fragment))
    std::cerr << "Shader failed to load" << std::endl; 
    return 0;
}

std::cout << "dfsfsdf";
Window::clear();
Window::getDrawer()->draw(shape, &shader);
Window::render();

Regardless, you shouldn't be loading your shader from a file every frame. Do it once, check the error, then enter the main loop. Something like this (untested):

int main()
{
    Window::createWindow(800, 600, "Mama");
    Window::clearColor(124, 32, 125);

    sf::Shader shader;
    if(!shader.loadFromFile("fragment.fs", sf::Shader::Fragment))
    {
        std::cerr << "Failed to load shader" << std::endl;
        return 0;
    }

    bool running = true;

    while(running){
        if(Window::isWindowClosed())
            running = false;

        sf::RectangleShape shape(sf::Vector2f(20, 20));
        shape.setPosition(10, 10);

        Window::clear();
        Window::getDrawer()->draw(shape, &shader);
        Window::render();
    }
}

Upvotes: 1

Related Questions