SFML 2.0 c++ sprite in array/vector - c++

I have this in my file blocks.h:
#include <vector>
class Blocks{
public:
string files_name[4];
vector < Sprite > sprites;
void load(){
for(int i=0;i<=sizeof(files_name);i++){
Texture my_texture;
my_texture.loadFromFile(this->files_name[i]);
sprites[i].setTexture( my_texture );
}
}
Blocks(){
this->files_name[0] = "wall.png";
this->files_name[1] = "floor.png";
this->files_name[2] = "live.png";
this->files_name[3] = "coins.png";
this->load();
}
void show(int id, int X, int Y){
sprites[id].setPosition(X, Y);
window.draw(sprites[id]);
}
};
I have no errors, but my game crashed. I think, the problem is in the line which reads sprites[i].setTexture(...)
I only have the message: Process terminated with status -1073741819 (0 minutes, 2 seconds)
My IDE is Code::Blocks 10.05, and I have Windows 8.
Of course, in the file main.cpp, I have defined the window:
RenderWindow window( VideoMode(920, 640, 32 ), "Game" );
#include "blocks.h"
Blocks BLOCKS;
----UPDATE:
Ok, now it's not crashing, thanks! But, now I can't see textures! I read the post by Benjamin Lindley and I added a new vector with textures. My code looks like this now:
const int arraySize = 4;
string files_name[4];
vector < Sprite > sprites;
vector < Texture > textures;
and, in load(), I have:
for(int i = 0; i < arraySize; i++){
Texture new_texture;
new_texture.loadFromFile(this->files_name[i]);
textures.push_back(new_texture);
sprites[i].setTexture(textures[i]);
and then it crashes again!
---UPDATE: Now I have again changed my code and I don't have a crash, but my textures are white squares. My texture live.png works, but the other textures are white! Here's my new code:
Sprite new_sprite;
new_sprite.setTexture(textures[i]);
sprites.push_back(new_sprite);

The problem is this line:
for(int i=0;i<=sizeof(files_name);i++){
If you print out the value of sizeof(files_name), you will find that it is 16 instead of 4! Don't use sizeof here. Also, don't use <= here, since even if you had replaced sizeof(files_name) with 4, you would have tried to access files_name[4], which would also give you an error.
Instead you could use:
const int arraySize = 4;
string files_name[arraySize];
...
for(int i = 0; i < arraySize; i++)
or something of that sort.
Also, hopefully you initialize sprites at some point. You need to fill your vector with Sprites (with something like sprites.push_back(mySprite)) before you call load().

SFML sprites store their associated textures by pointer. The textures you are creating are local to the loop, and so are destroyed at the end of each iteration, thereby invalidating the pointer in the sprite. You need to keep your textures alive for the duration of whatever sprite uses them.
Also, your sprites vector has no elements, you need to either specify a size, or use push_back in your loop.
Also, as Scott pointed out, sizeof(files_name) is not the appropriate terminating value for your loop, since that gives you sizeof(string) * number of elements in the array. You only want the number of elements in the array.

Ok, it works only in two loop: Thanks for helping :)
vector < Sprite > sprites;
vector < Texture > tekstures;
and:
for(int i = 0; i < arraySize; i++){
Texture new_texture;
new_texture.loadFromFile(this->files_name[i]);
tekstures.push_back(new_texture);
}
for(int i = 0; i < arraySize; i++){
Sprite new_sprite;
new_sprite.setTexture(tekstures[i]);
sprites.push_back(new_sprite);
}
and in one loop it doesn't work, i have white textures:
for(int i = 0; i < arraySize; i++){
Texture new_texture;
new_texture.loadFromFile(this->files_name[i]);
tekstures.push_back(new_texture);
Sprite new_sprite;
new_sprite.setTexture(tekstures[i]);
sprites.push_back(new_sprite);
}
Greetings !

Related

Issue with drawn object speeding up in a loop

So I have an assignment where I have to get bugs to draw to the screen (no problem) and then shoot off from the bugbag drawn at the bottom of the screen (also no problem). However, my issue is that when the code loops, the speed picks up for some reason and everything I've tried to move around to fix the issue has proved fruitless. I either get it to slow was day (but not loop through the amount taken in) or nothing changes. Here is a code snippet from where the loop resides, I can provide more if need be, but I'm positive the problem stems from this method.
Point2D creatureThrow(Creature& myCreature, BugBag& theBag)
{
//Added for creature
Point2D creatureLocation = Point2D(CREATURE_DRAW_LEFT, 0);
int startingBugCount = theBag.getBugCount();
//std::vector<Bug> deadBugs(startingBugCount);
//Create bug
Bug* bug = new Bug();
// Display all the bugs
for (int bugNumber = 1; bugNumber <= startingBugCount; bugNumber++)
{
bug->moveTo(0, -90);
for (int step = 0; step < BUG_STEP_SIZE; step++) // 20 is the number of steps
{
gdsWindow.clear();
for (int j=0; j < bugNumber; j++) //move bugs
{
//bug->draw();
bug->moveBy(0, 8);
}
myCreature.draw();
theBag.draw();
bug->draw();
Sleep(FRAME_SLEEP);
}
}
return creatureLocation;
}

I am creating array of sprites and they should appare randomly but its happening?

I am trying to create array sprites which contain 5 sprites as 0.png, 1.png, 2.png, 3.png, 4.png.
I want them to appear randomly on the screen.
Below is my code but its not working, any help?
std::vector <CCSprite*> _sprites;
_sprites.reserve(10);
int spritearray[5] = { 0.png,1.png,2.png,3.png,4.png }; // I AM GETTING ERROR HERE?
int i;
for(i=0;i<5;i++)
{
CCSprite* foo = new cocos2d::CCSprite();
int index = rand() % 5;
// foo->initWithFile(index);
foo->setPosition(ccp(60,50*i));
_sprites.push_back(foo); //store our sprites to do other stuffs later
this->addChild(foo,1);
}
Your "logic" currently is fine, it's the implementation that you have problem with.
If you check the initWithFile function, you see that it takes a file name as a string.
So you need to make an array of strings (the file names) and not an array of integers. Then you use the random index as index into this file-name array and pass it as argument to the initWithFile function.
Ok, you are using the same code I provided you before:
std::vector <CCSprite*> _sprites;
_sprites.reserve(10);
std::vector<std::string> _spriteNames = {"0.png", "1.png", "2.png", "3.png", "4.png"};
for (int i=0;i < _spriteNames.size(); i++)
{
CCSprite* foo = cocos2d::CCSprite::create(_spriteNames.at(i));
int random = rand() % 5;
foo->setPosition(CCPoint((60 * random), (50 * random)));
_sprites.push_back(foo); // <- store your sprites to do stuff to them later.
addChild(foo, 1); //<-- this is adding the child.
}

Add 1 to vector<unsigned char> value - Histogram in C++

I guess it's such an easy question (I'm coming from Java), but I can't figure out how it works.
I simply want to increment an vector element by one. The reason for this is, that I want to compute a histogram out of image values. But whatever I try I just can accomplish to assign a value to the vector. But not to increment it by one!
This is my histogram function:
void histogram(unsigned char** image, int height,
int width, vector<unsigned char>& histogramArray) {
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
// histogramArray[1] = (int)histogramArray[1] + (int)1;
// add histogram position by one if greylevel occured
histogramArray[(int)image[i][j]]++;
}
}
// display output
for (int i = 0; i < 256; i++) {
cout << "Position: " << i << endl;
cout << "Histogram Value: " << (int)histogramArray[i] << endl;
}
}
But whatever I try to add one to the histogramArray position, it leads to just 0 in the output. I'm only allowed to assign concrete values like:
histogramArray[1] = 2;
Is there any simple and easy way? I though iterators are hopefully not necesarry at this point, because I know the exakt index position where I want to increment something.
EDIT:
I'm so sorry, I should have been more precise with my question, thank you for your help so far! The code above is working, but it shows a different mean value out of the histogram (difference of around 90) than it should. Also the histogram values are way different than in a graphic program - even though the image values are exactly the same! Thats why I investigated the function and found out if I set the histogram to zeros and then just try to increase one element, nothing happens! This is the commented code above:
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
histogramArray[1]++;
// add histogram position by one if greylevel occured
// histogramArray[(int)image[i][j]]++;
}
}
So the position 1 remains 0, instead of having the value height*width. Because of this, I think the correct calculation histogramArray[image[i][j]]++; is also not working properly.
Do you have any explanation for this? This was my main question, I'm sorry.
Just for completeness, this is my mean function for the histogram:
unsigned char meanHistogram(vector<unsigned char>& histogram) {
int allOccurences = 0;
int allValues = 0;
for (int i = 0; i < 256; i++) {
allOccurences += histogram[i] * i;
allValues += histogram[i];
}
return (allOccurences / (float) allValues) + 0.5f;
}
And I initialize the image like this:
unsigned char** image= new unsigned char*[width];
for (int i = 0; i < width; i++) {
image[i] = new unsigned char[height];
}
But there shouldn't be any problem with the initialization code, since all other computations work perfectly and I am able to manipulate and safe the original image. But it's true, that I should change width and height - since I had only square images it didn't matter so far.
The Histogram is created like this and then the function is called like that:
vector<unsigned char> histogramArray(256);
histogram(array, adaptedHeight, adaptedWidth, histogramArray);
So do you have any clue why this part histogramArray[1]++; don't increases my histogram? histogramArray[1] remains 0 all the time! histogramArray[1] = 2; is working perfectly. Also histogramArray[(int)image[i][j]]++; seems to calculate something, but as I said, I think it's wrongly calculating.
I appreciate any help very much! The reason why I used a 2D Array is simply because it is asked for. I like the 1D version also much more, because it's way simpler!
You see, the current problem in your code is not incrementing a value versus assigning to it; it's the way you index your image. The way you've written your histogram function and the image access part puts very fine restrictions on how you need to allocate your images for this code to work.
For example, assuming your histogram function is as you've written it above, none of these image allocation strategies will work: (I've used char instead of unsigned char for brevity.)
char image [width * height]; // Obvious; "char[]" != "char **"
char * image = new char [width * height]; // "char*" != "char **"
char image [height][width]; // Most surprisingly, this won't work either.
The reason why the third case won't work is tough to explain simply. Suffice it to say that a 2D array like this will not implicitly decay into a pointer to pointer, and if it did, it would be meaningless. Contrary to what you might read in some books or hear from some people, in C/C++, arrays and pointers are not the same thing!
Anyway, for your histogram function to work correctly, you have to allocate your image like this:
char** image = new char* [height];
for (int i = 0; i < height; ++i)
image[i] = new char [width];
Now you can fill the image, for example:
for (int i = 0; i < height; ++i)
for (int j = 0; j < width; ++j)
image[i][j] = rand() % 256; // Or whatever...
On an image allocated like this, you can call your histogram function and it will work. After you're done with this image, you have to free it like this:
for (int i = 0; i < height; ++i)
delete[] image[i];
delete[] image;
For now, that's enough about allocation. I'll come back to it later.
In addition to the above, it is vital to note the order of iteration over your image. The way you've written it, you iterate over your columns on the outside, and your inner loop walks over the rows. Most (all?) image file formats and many (most?) image processing applications I've seen do it the other way around. The memory allocations I've shown above also assume that the first index is for the row, and the second is for the column. I suggest you do this too, unless you've very good reasons not to.
No matter which layout you choose for your images (the recommended row-major, or your current column-major,) it is in issue that you should always keep in your mind and take notice of.
Now, on to my recommended way of allocating and accessing images and calculating histograms.
I suggest that you allocate and free images like this:
// Allocate:
char * image = new char [height * width];
// Free:
delete[] image;
That's it; no nasty (de)allocation loops, and every image is one contiguous block of memory. When you want to access row i and column j (note which is which) you do it like this:
image[i * width + j] = 42;
char x = image[i * width + j];
And you'd calculate the histogram like this:
void histogram (
unsigned char * image, int height, int width,
// Note that the elements here are pixel-counts, not colors!
vector<unsigned> & histogram
) {
// Make sure histogram has enough room; you can do this outside as well.
if (histogram.size() < 256)
histogram.resize (256, 0);
int pixels = height * width;
for (int i = 0; i < pixels; ++i)
histogram[image[i]]++;
}
I've eliminated the printing code, which should not be there anyway. Note that I've used a single loop to go through the whole image; this is another advantage of allocating a 1D array. Also, for this particular function, it doesn't matter whether your images are row-major or column major, since it doesn't matter in what order we go through the pixels; it only matters that we go through all the pixels and nothing more.
UPDATE: After the question update, I think all of the above discussion is moot and notwithstanding! I believe the problem could be in the declaration of the histogram vector. It should be a vector of unsigned ints, not single bytes. Your problem seems to be that the value of the vector elements seem to stay at zero when your simplify the code and increment just one element, and are off from the values they need to be when you run the actual code. Well, this could be a symptom of numeric wrap-around. If the number of pixels in your image are a a multiple of 256 (e.g. 32x32 or 1024x1024 image) then it is natural that the sum of their number would be 0 mod 256.
I've already alluded to this point in my original answer. If you read my implementation of the histogram function, you see in the signature that I've declared my vector as vector<unsigned> and have put a comment above it that says this victor counts pixels, so its data type should be suitable.
I guess I should have made it bolder and clearer! I hope this solves your problem.

C++ Using 3D Dynamic Arrays and Vectors

I'm new to C++ and getting a bit frustrated with it. Below, in pixelsVector, I am storing each pixel RGB float-value in Pixel and want to dump
all the values to a byte array with pixelsArray so I can output to an image file. HEIGHT and WIDTH refer to the image dimensions. The code below works fine, but I need to specify
the sizes of pixelsArray at run-time, because it may not always be a 500x500 image.
// WIDTH and HEIGHT specified at run-time
vector<vector<Pixel>> pixelsVector (WIDTH, vector<Pixel> (HEIGHT));
...
unsigned char pixelsArray[500][500][3];
for (int i = 0; i < 500; i++)
{
for (int j = 0; j < 500; j++)
{
// Returns RGB components
vector<float> pixelColors = pixelArray[i][j].getColor();
for (int k = 0; k < 3; k++)
{
pixels[i][j][k] = pixelColors.at(k);
}
}
}
// write to image file
fwrite(pixelsArray, 1, 500*500*3, file);
If I put HEIGHT and WIDTH instead of 500 and 500 above, I get an error since they are not constant values. Now using a 3D vector does seem to work, but fwrite won't take a vector for its first argument. I tried using a triple-pointer array but
it doesn't seem to work at all - maybe I was using it wrong. Here it is using a 3D vector for pixelsArray:
vector<vector<Pixel>> pixelsVector (WIDTH, vector<Pixel> (HEIGHT));
...
vector< vector< vector<unsigned char> > > pixelsArray;
for (int i = 0; i < HEIGHT; i++)
{
pixels.push_back(vector< vector<unsigned char> >());
for (int j = 0; j < WIDTH; j++)
{
pixels[i].push_back(vector<unsigned char>());
vector<float> pixelColors;
pixelColors = pixelArray[i][j].getColor();
for (int k = 0; k < 3; k++)
{
pixels[i][j][k] = pixelColors.at(k);
}
}
}
// Error
fwrite(pixelsArray, 1, 500*500*3, file);
Suggestions?
You could use Boost.MultiArray insead of vectors of vectors, which lets you access he underlying memory with the .data() method.
It looks like you are trying to manipulate images, so you might want to consider using Boost.Gil.
From the last code snippet:
vector<vector<Pixel>> pixelsVector (WIDTH, vector<Pixel> (HEIGHT));
Using uppercase names for variables you risk name collisions with macros. In C++ all uppercase names are conventionally reserved for macros.
...
vector< vector< vector<unsigned char> > > pixelsArray;
Presumably this vector is the same as is called pixels below?
If so, then the standard advice is that it helps to post real code.
Anyway, in order to output those bytes in one efficient operation you need the bytes to be contiguously stored in memory. So a vector of vectors of vectors is out. Use a single vector (C++ guarantees contiguous storage for the buffer of a std::vector).
for (int i = 0; i < HEIGHT; i++)
{
pixels.push_back(vector< vector<unsigned char> >());
for (int j = 0; j < WIDTH; j++)
{
pixels[i].push_back(vector<unsigned char>());
At this point you have an inner vector but it's empty, size 0.
vector<float> pixelColors;
pixelColors = pixelArray[i][j].getColor();
Presumably pixelArray is an instance of a class you have defined?
for (int k = 0; k < 3; k++)
{
pixels[i][j][k] = pixelColors.at(k);
}
Here you're trying to assign to non-existent elements of the empty innermost vector. You can either size it properly in advance, or use the push_back method for each value.
In addition, are you sure that the float values are integers in range 0 through 255 (or more generally, 0 through UCHAR_MAX) and not, say, in the range 0 through 1?
Perhaps you need to scale those values.
}
}
// Error
fwrite(pixelsArray, 1, 500*500*3, file);
If pixelsArray had been a (non-empty) vector of bytes, then you could use &pixelsArray[0] to obtain a pointer to the first byte.
Now, I know, the above only dissects some of what's wrong, and doesn't tell you directly what's right. :-)
But some more information would be needed to give example code for doing this, like (1) what are your float values, and (2) what do you want in your file?
Anyway, hope this helps,
– Alf

Shape object in Processing, translate individual shapes

I am facing difficulty with the translate() function for objects as well as objects in general in Processing. I went through the examples and tried to replicate the manners by which they instantiated the objects but cannot seem to even get the shapes to appear on the screen no less move them. I instantiate the objects into an array using a nested for loop and expect a grid of the objects to be rendered. However, nothing at all is rendered.
My nested for loop structure to instantiate the tiles:
for(int i=0; i<102; i++){
for(int j=0; j<102; j++){
tiles[i][j]=new tile(i,0,j);
tiles[i][j].display();
}
}
And the constructors for the tile class:
tile(int x, int y, int z){
this.x=x;
this.y=y;
this.z=z;
beginShape();
vertex(x,y,z);
vertex(x+1,y,z);
vertex(x+1,y,z-1);
vertex(x,y,z-1);
endShape();
}
Nothing is rendered at all when this runs. Furthermore, if this is of any concern, my translations(movements) are done in a method I wrote for the tile class called move which simply calls translate. Is this the correct way? How should one approach this? I can't seem to understand at all how to render/create/translate individual objects/shapes.
Transformations (such as translate, rotate, etc) do not work if you use beginShape() as you're simply specifying direct coordinates to draw to. If you're relying on the result of a translate to put an object into a visible location that could be why you're not having any results.
Also, depending on how you're looking at your scene, you probably have z coming towards the camera, so your objects are being drawn with you looking at them on the side, and since they are 2d objects you won't see anything, try using x/y or y/z instead of x/z which you are doing right now.
You can definitely use pushMatrix() and translate() with beginShape() and such, it may be not completely what you expect, but it will definitely move the things around from the default origin.
What is going wrong with your above example is that you are putting the drawing() code in the constructor where you should be putting it in the display function.
so:
public void display(Processing proc) {
proc.beginShape()
etc.
}
display() also needs to be called in the draw() loop, so initialize your tiles once and then display them in draw().
You should follow #Tyler's advice on drawing in a 2D plane(x/y, y/z, x/z).
Your shapes probably do not render because you might be drawing them once, and clearing the screen in the draw() method, but I'm not sure as I can't see the rest of your code.
Here's what I mean:
tile[][] tiles;
int numTiles = 51;//x and y number of tiles
void setup() {
size(400,400,P3D);
tiles = new tile[numTiles][numTiles];
for(int i=0; i<numTiles; i++)
for(int j=0; j<numTiles; j++)
tiles[i][j]=new tile(i,j,0,5);
}
void draw() {
background(255);
translate(width * .5,height * .5);
rotateY((float)mouseX/width * PI);
rotateX((float)mouseY/height * PI);
for(int i=0; i<numTiles; i++)
for(int j=0; j<numTiles; j++)
tiles[i][j].display();
}
class tile {
int x,y,z;
tile(int x, int y, int z,int s) {//s for size
this.x=x * s;
this.y=y * s;
this.z=z * s;
}
void display(){
beginShape(QUADS);
//XY plane
//*
vertex(x,y,z);
vertex(x+x,y,z);
vertex(x+x,y+y,z);
vertex(x,y+y,z);
//*/
endShape();
}
}
Since you're only drawing squares, you could use the rect() function.
int numSquares = 51,squareSize = 10;
void setup(){
size(400,400,P3D);
smooth();
}
void draw(){
background(255);
translate(width * .5, height * .5);
rotateY((float)mouseX/width * PI);
for(int j = 0 ; j < numSquares ; j++)
for(int i = 0 ; i < numSquares ; i++)
rect(i*squareSize,j*squareSize,squareSize,squareSize);
}
HTH