0

I have a problem with trying to make procedural textures in SFML i have this code

sf::Texture* CreateTexture(int w, int h){
   sf::Image tempImage;
   sf::Texture* Tex = new sf::Texture();
   Tex->create(w,h);
   sf::Uint8 *pixelData = GeneratePNoise(w,h);

   tempImage.create(w, h, pixelData);
   Tex->update(tempImage);
   //Tex->loadFromImage(tempImage);
   return Tex;
}
sf::Uint8* GeneratePNoise(int w,int h){
   std::vector<sf::Uint8> data(w*h*4);

   for (int i=0;i<w*h*4;i++){
     data[i]=128;
     if (i+1%4)data[i]=255;
   }

   return data.data();
}
sf::Texture CreateTexturens(int w, int h){
   sf::Image tempImage;
   sf::Texture Tex;
   Tex.create(w,h);
   sf::Uint8 *pixelData = GeneratePNoise(w,h);

   tempImage.create(w, h, pixelData);
   Tex.update(tempImage);
   return Tex;
}

I also have this code which uses the above code

void Star::createStar(){
   sf::CircleShape star(r,30);
   star.setPosition(x,y);
   sf::Texture* t = CreateTexture(256,256);
   star.setTexture(t,false);
   std::cout << "Done!"<<std::endl;
}

This doesn't seem to render anything, I believe it is about the code revolving around creating and applying the texture, all help is appreciated!

Reyno
  • 583
  • 13
  • 28
Slymodi
  • 185
  • 3
  • 13

1 Answers1

2

In the GeneratePNoise() function, you are returning the data() from a vector that is going to be destroyed upon the returning of that function, and thus the data won't be available anymore.

Instead of a vector, I would recommend creating a unique_ptr and returning that unique_ptr from the function, such as:

unique_ptr<sf::Uint8[]> GeneratePNoise(int w, int h) 
{
    unique_ptr<sf::Uint8[]> data(new sf::Uint8[w * h * 4]);

    for (int i = 0; i  < w * h * 4; i++) {
      data[i] = 128;
      if (i + 1 % 4) 
         data[i] = 255;
    }

    return data;
}

In that case you don't even need to delete the resource that was returned. You should do the same with the CreateTexture() function.

LLLL
  • 373
  • 2
  • 5
  • Try adding #include , or using std::unique_ptr, or perhaps enabling your compiler's -std=c++0x flag – LLLL Jun 25 '13 at 19:49
  • and now I get Error 2 error C2440: 'initializing' : cannot convert from 'std::unique_ptr<_Ty>' to 'sf::Uint8 *' – Slymodi Jun 25 '13 at 19:51
  • Those have to do with what the GeneratePNoise(int w, int h); is outputting, and the use in the other two mthods – Slymodi Jun 25 '13 at 19:54
  • Try changing sf::Uint8 *pixelData = GeneratePNoise(w,h); to auto pixelData = GeneratePNoise(w,h);, and tempImage.create(w, h, pixelData); to tempImage.create(w, h, pixelData.get()); – LLLL Jun 25 '13 at 19:56
  • It compiled, but there is no image showing up, it may do with the createstar function! – Slymodi Jun 25 '13 at 21:03
  • nevermind that, I fixed some of the render code, it works thanks! – Slymodi Jun 25 '13 at 22:19