How to write a Copy Constructor for a Sprite? - c++

My code crashes and I think I need to deep copy p_Texture and sprite.
I know how to make a deep copy of a pointer to an array but I'm not sure sure how to do this. Here I wrote this destructor:
class Sprite
{
private:
IDirect3DTexture9* p_Texture;
LPD3DXSPRITE sprite;
D3DXVECTOR3 imagepos;
int m_posX;
int m_posY;
int m_posZ;
int m_width, m_heigth;
public:
Sprite()
{
}
~Sprite()
{
if (sprite)
{
sprite->Release();
sprite = 0;
}
if (p_Texture)
{
p_Texture->Release();
p_Texture = 0;
}
}
Sprite(std::string path, int posX, int posY, int posZ, int width, int heigth)
{
m_posX = posX;
m_posY = posY;
m_posZ = posZ;
m_width = width;
m_heigth = heigth;
imagepos.x = posX;
imagepos.y = posY;
imagepos.z = posZ;
D3DXCreateTextureFromFileEx(p_Device, path.c_str(), m_width, m_heigth, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_DEFAULT,
D3DX_DEFAULT, D3DX_DEFAULT, 0, NULL, NULL, &p_Texture)
D3DXCreateSprite(p_Device, &sprite)
}
void draw()
{
sprite->Begin(D3DXSPRITE_ALPHABLEND);
sprite->Draw(p_Texture, NULL, NULL, &imagepos, 0xFFFFFFFF);
sprite->End();
}
void incPosX(int x) {imagepos.x += x;}
void decPosX(int x) {imagepos.x -= x;}
void incPosY(int x) {imagepos.y += x;}
void decPosY(int x) {imagepos.y -= x;}
float getPosX() { return imagepos.x; }
float getPosY() { return imagepos.y; }
};
However, it crashes because of copying it in the code.

The syntax for a copy constructor is:
Sprite::Sprite(Sprite& other)
Then you just copy what you need from other to the this pointer.
Your code as it is right now has an implicit copy and move constructor. Both copy everything by value.
The reason for your crashing is likely because somewhere a copy or move of a Sprite is made, and when it expires the destructor is called. This frees some resources which you later attempt to use.
You can find such places by deleteing your copy and move constructors, and seeing where the compiler complains. The syntax follows:
Sprite::Sprite(sprite& other) = delete; // no copy constructor
Sprite::Sprite(Sprite&& other) = delete; // no move constructor

Related

SFML performance issue in space invader like game

I'm trying to learn C++, and I'm making this little space-invader-like game to get better at it.
Currently everything works just fine but for some reason the performance of the game is kind of terrible considering how simple the graphics are (the game runs smoothly for a while and then stops for like half a second, constantly).
I'm pretty sure the lag is due to the amount of bullets I'm removing and creating from the vector containing them (I'm removing the bullets that go outside the screen because there's no point in updating them or rendering them). So how could I fix this?
I checked the game loop and the problem isn't there.
Code below
player.h:
#pragma once
#include <vector>
#include <iostream>
#include "entity.h"
#include "SFML/Graphics.hpp"
#include "vector.h"
class Player : public Entity {
private:
int f_lastshot = 0;
const double shoot_delay = 0.5;
const float bullet_speed = 1, speed = 0.75;
std::vector<Entity> bullets;
sf::Clock *c;
sf::Sprite bullet_sprite;
public:
Player(Vector &pos, int w, int h, sf::Sprite &spr);
~Player();
void init();
void update();
void render(Window &win);
void shoot();
};
player.cpp:
#include "player.h"
Player::Player(Vector &pos, int w, int h, sf::Sprite &spr) : Entity() {
this->pos = pos;
this->sprite = spr;
this->width = w;
this->height = h;
float scale_x = (float)w / (float)spr.getTexture()->getSize().x;
float scale_y = (float)h / (float)spr.getTexture()->getSize().y;
sprite.setScale(scale_x, scale_y);
}
void Player::update() {
if (sf::Mouse::isButtonPressed(sf::Mouse::Left) || sf::Keyboard::isKeyPressed(sf::Keyboard::S)) {
if ((double)(f_lastshot / 60) > shoot_delay) // shoot only if enough time has passed
shoot();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) dir.setX(-speed); // move left
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) dir.setX(speed); // move right
else dir.setX(0); // stop if no button is being pressed
f_lastshot++;
pos = pos + dir; // add the direction to the position
for (Entity &e : bullets) {
e.update(); // update each bullet
if (e.getPos().getY() < 0) // if the bullet is outside the screen delete it
bullets.erase(bullets.begin());
}
}
void Player::render(Window &win) {
sprite.setPosition(pos.getX(), pos.getY()); // update the position of the sprite
win.render(sprite);
for (Entity &bullet : bullets)
bullet.render(win);
}
void Player::shoot() {
f_lastshot = 0;
bullets.push_back(Entity::Entity(Vector::Vector(pos.getX() + width / 2 - 8, pos.getY()), 16, 32, bullet_sprite, Vector::Vector(0,-bullet_speed)));
}
void Player::init() {
if (c == nullptr) c = new sf::Clock();
else c->restart();
dir.setX(0); dir.setY(0);
sf::Texture *bullet_texture = new sf::Texture();
if (!bullet_texture->loadFromFile("bullet.png"))
std::cerr << "Could not load bullet image" << std::endl;
bullet_sprite.setTexture(*bullet_texture);
}
Player::~Player() {
delete bullet_sprite.getTexture();
delete c;
}
entity.h:
#pragma once
#include <SFML/Graphics.hpp>
#include <iostream>
#include "vector.h"
#include "window.h"
class Entity {
protected:
Vector pos;
sf::Sprite sprite;
int width, height;
Vector dir; // the direction
public:
Entity();
Entity(Vector &pos, int w, int h, sf::Sprite &spr);
Entity(Vector pos, int w, int h, sf::Sprite &spr);
Entity(Vector pos, int w, int h, sf::Sprite &spr, Vector dir);
void update();
void render(Window &win);
bool collides(Entity &other) const;
public:
Vector getPos() const;
Vector getDirection() const;
sf::Sprite getSprite() const;
int getWidth() const;
int getHeight() const;
void setPos(Vector &pos);
void setWidth(int width);
void setHeight(int height);
void setSize(int width, int height);
void setSprite(sf::Sprite &sprite);
void setDirection(Vector dir);
};
entity.cpp:
#include "entity.h"
Entity::Entity() {}
Entity::Entity(Vector &pos, int w, int h, sf::Sprite &spr)
: pos(pos), width(w), height(h) {
this->sprite = spr;
float scale_x = (float)w/(float)spr.getTexture()->getSize().x;
float scale_y = (float)h/(float)spr.getTexture()->getSize().y;
sprite.setPosition(pos.getX(), pos.getY());
sprite.setScale(scale_x, scale_y);
}
Entity::Entity(Vector pos, int w, int h, sf::Sprite &spr)
: pos(pos), width(w), height(h) {
this->sprite = spr;
float scale_x = (float)w / (float)spr.getTexture()->getSize().x;
float scale_y = (float)h / (float)spr.getTexture()->getSize().y;
sprite.setPosition(pos.getX(), pos.getY());
}
Entity::Entity(Vector pos, int w, int h, sf::Sprite &spr, Vector dir)
: pos(pos), width(w), height(h) {
this->sprite = spr;
this->dir = dir;
float scale_x = (float)w / (float)spr.getTexture()->getSize().x;
float scale_y = (float)h / (float)spr.getTexture()->getSize().y;
sprite.setPosition(pos.getX(), pos.getY());
}
bool Entity::collides(Entity &other) const {
bool x_coll = (pos.getX() + width> other.getPos().getX() && pos.getX()< other.getPos().getX())||(pos.getX() < other.getPos().getX() + other.getWidth() && pos.getX() > other.getPos().getX());
bool y_coll = (pos.getY() + height > other.getPos().getY() && pos.getY() < other.getPos().getY()||(pos.getY() < other.getPos().getY() + other.getHeight() && pos.getY() > other.getPos().getY()));
return (x_coll && y_coll);
}
void Entity::render(Window &win) {
sprite.setPosition(pos.getX(), pos.getY());
win.render(sprite);
}
void Entity::update() {
pos = pos + dir;
}
Vector Entity::getPos() const { return pos; }
int Entity::getWidth() const { return width; }
int Entity::getHeight() const { return height; }
sf::Sprite Entity::getSprite() const { return sprite; }
Vector Entity::getDirection() const { return dir; }
void Entity::setPos(Vector &pos) { this->pos = pos; }
void Entity::setWidth(int width) { this->width = width; }
void Entity::setHeight(int height) { this->height = height; }
void Entity::setSprite(sf::Sprite &sprite) { this->sprite = sprite; }
void Entity::setDirection(Vector dir) { this->dir = dir; }
void Entity::setSize(int width, int height) {
this->width = width;
this->height = height;
}
To identify bottlenecks and other performance issues you should use a profiler. Only by looking the code it's hard if not impossible to find the correct places that need optimisation. But one problem is indeed the way you remove bullets:
for (Entity &e : bullets) {
e.update(); // update each bullet
if (e.getPos().getY() < 0) // if the bullet is outside the screen delete it
bullets.erase(bullets.begin());
}
There is a logic error. You check if the current bullet e is outside the screen, but then delete the first one anyway. This can't be right.
It's extremely inefficient to delete the first element of a std::vector, because all the following elements will have to be moved one place left. This happens for every bullet you remove!
It may cause undefined behavior. The reference says that erase
Invalidates iterators and references at or after the point of the erase, including the end() iterator.
Changing the size of a vector while iterating over it is usually a bad idea.
To overcome those issues you could use the Erase-Remove-Idiom like this:
// Update as usual
for (Entity &e : bullets) {
e.update();
}
// Erase-Remove bullets that are out of screen
bullets.erase(std::remove_if(bullets.begin(), bullets.end(),
[](const Entity &e){ return e.getY() < 0;}), bullets.end());

Debug Assertion failed on making copy constructor

I am trying to make a copy constructor because I have a pointer in my class. However, I got runtime error "Debug Assertion failed" and I do not know what to do. I have two classses, MyMatrix and MyImage. I want to write a copy constructor for MyImage, therefore I also write one for MyMatrix.
class MyMatrix{
private:
unsigned _width, _height;
unsigned char *_data;
public:
MyMatrix(MyMatrix &other);
}
MyMatrix::MyMatrix(MyMatrix &other) {
_width = other._width;
_height = other._height;
_data = new unsigned char[_width*_height];
memcpy(_data, other._data, _width*_height*sizeof(unsigned char));
}
class MyImage {
public:
int _width;
int _height;
MyMatrix _Y; //gray level
}
MyImage::MyImage(MyImage &other) {
_width = other._width;
_height = other._height;
_Y = MyMatrix(other._Y);
}
int main(){
char *filename = "hw1_images/p1/house.raw"; //some raw image
int width = 512;
int height = 512;
//read the image
MyImage inputImage(filename, width, height, fileMode::CFA);
//copy the image
MyImage test(inputImage);
return 0;
}
I got error even if I comment the memcry(). If I use std::cout to display the value of my copy, it is alway 221. Please help me with it. Thank you.
You are writing _Y = MyMatrix(other._Y);, I expect that you have defined the assignement operator for your Matrix class : MyMatrix & operator(const MyMatrix & other); otherwise the compiler will create a default one for you that just copy your attributes, meaning your pointer will be copied, not the content.
And, as I see that you can manipulate an important size of data and if you have c++11 enabled, I would definitely look at the copy swap idiom : What is the copy-and-swap idiom?
If its just matter of crash then you may do something like below.
class MyMatrix{
private:
unsigned _width, _height;
unsigned char *_data;
public:
MyMatrix(){
_width = 2;
_height = 3;
_data = new unsigned char[sizeof(unsigned char)];
}
MyMatrix(MyMatrix &other);
};
MyMatrix::MyMatrix(MyMatrix &other) {
_width = other._width;
_height = other._height;
_data = new unsigned char[(_width*_height) + 1];
memcpy(_data, other._data, _width*_height*sizeof(unsigned char));
}

C++ Vector Size is Zero

I am trying to create a function that renders everything in a vector of displayobject objects (on another thread). I am using SDL thread.
Here is the displayobject.h:
class DisplayObject
{
protected:
int width;
int height;
int x;
int y;
SDL_Texture* texture;
SDL_Renderer* renderer;
public:
~DisplayObject();
int getX();
void setX(int x);
int getY();
void setY(int y);
int getWidth();
void setWidth(int width);
int getHeight();
void setHeight(int height);
SDL_Texture* getTexture();
SDL_Renderer* getRenderer();
};
In graphics.h I have these variables:
std::vector<DisplayObject> imgArr;
SDL_Thread* renderThread;
static int renderLoop(void* vectorPointer);
This code is in the graphics constructor:
TextLabel textLabel(graphics->getRenderer(), 300, 80, "Hallo Welt", 50, Color(255, 0, 255), "Xenotron.ttf");
//TextLabel inherits from DisplayObject
imgArr.push_back(textLabel);
renderThread = SDL_CreateThread(Graphics::renderLoop, "renderLoop", &imgArr);
This is the render loop function:
int Graphics::renderLoop(void* param)
{
int counter = 0;
bool rendering = true;
std::vector<DisplayObject>* imgArr = (std::vector<DisplayObject>*)param;
while (rendering)
{
cout << imgArr->size() << endl;
counter++;
if (counter > 600)
{
rendering = false;
}
SDL_Delay(16);
}
return 0;
}
The problem is that it only prints 0's in the console. Why does it do that? It is supposed to write 1 since I pushed on object into it.
When you insert a TextLabel into std::vector<DisplayObject>, what is stored in the vector is not your original TextLabel object, but a DisplayObject copy-constructed from the TextLabel. What you want to do is create your TextLabels with new, store pointers to them, and call delete when you no longer need them.
The best solution would be to use boost::ptr_vector<DisplayObject> instead - it will automatically call delete when you erase objects from it.
http://www.boost.org/doc/libs/1_57_0/libs/ptr_container/doc/ptr_container.html
If you can't use Boost, but can use C++11, you can use std::vector<std::unique_ptr<DisplayObject>>.

Strange destructor call in C++

I have those inheritance classes :
Base Class: Entity
Derived from Entity Classes: Actor, Obj, Enemy
The Base class Entity contains an obj of a user-defined-type that i called "CollisionStuff".
When i run my program the destructor of CollisionStuff is called after every CollisionStuff constructor call and every time game-loop goes on.
so my call is: why is this happening?
As you can see below, i allocate dinamically some arrays in the setRectangle method, the programm calls the destructor, it deletes my data and when i try to use them... it calls "_ASSERTE(_BLOCK_TYPE_IS_VALID(pHead->nBlockUse));".
Thank you in before
here my code: Entity.h
enum e_Type {tActor = 0, tObj, tEnemy, tBackg};
class Entity
{
public:
Entity(void);
~Entity(void);
float getH();
float getW();
void setWH(float W, float H);
bool CreateSprite(std::string path);
sf::Sprite& getSprite();
void setType(e_Type type);
e_Type getType();
CollisionStuff getColStuff();
static std::list<Entity*> List;
protected:
sf::Sprite m_sprite;
sf::Texture m_texture;
float m_h;
float m_w;
e_Type m_type;
CollisionStuff m_colStuff;
void addToList();
};
CollisionStuff.h
class CollisionStuff
{
public:
CollisionStuff();
~CollisionStuff(void);
void setRectangle(int W, int H);
void followTheSprite(Entity entity);
private:
sf::Vector2f* m_a;
sf::Vector2f* m_b;
sf::Vector2f* m_c;
sf::Vector2f* m_d;
/* this member data are sides of rectangle used
to manage collisions between object throughout the scenario
a
-------------
| |
c | | d
| |
-------------
b
*/
};
CollisionStuff.cpp
CollisionStuff::CollisionStuff()
{
//setRectangle(0, 0);
}
void CollisionStuff::setRectangle(int W, int H)
{
m_a = new sf::Vector2f[W];
m_b = new sf::Vector2f[W];
m_c = new sf::Vector2f[H];
m_d = new sf::Vector2f[H];
}
void CollisionStuff::followTheSprite(Entity entity)
{
entity.getSprite().setOrigin(0, 0);
sf::Vector2f UpLeftVertex = entity.getSprite().getPosition();
for(int i = 0; i < entity.getW(); i++)
{
m_a[i].x = UpLeftVertex.x + i;
m_a[i].y = UpLeftVertex.y;
m_b[i].x = UpLeftVertex.x + i;
m_b[i].y = UpLeftVertex.y + entity.getH();
}
for(int i = 0; i < entity.getH(); i++)
{
m_c[i].x = UpLeftVertex.x;
m_c[i].y = UpLeftVertex.y + i;
m_d[i].x = UpLeftVertex.x + entity.getW();
m_d[i].y = UpLeftVertex.y + i;
}
}
CollisionStuff::~CollisionStuff(void)
{
delete [] m_a;
delete [] m_b;
delete [] m_c;
delete [] m_d;
}
EDIT
Thank you for the answers.
Example of CollisionStuff use
Actor.cpp (it's a derived class of Entity)
Actor::Actor(void)
{
if(!CreateSprite("D://Sprites//MainChar.png"))
{
std::cout << "Impossibile creare sprite" << std::endl;
}
else
{
std::cout << "Creazione sprite riuscita" << std::endl;
m_sprite.setPosition(100.0f, 365.0f);
m_sprite.setOrigin(20, 35);
//m_sprite.setPosition(190.0f, 382.5f); // 200, 400
setWH(40, 70);
m_health = 100;
m_status = Good;
setType(tActor);
m_jCounter = -1;
m_action = Null;
setColStuff();
}
}
void Actor::setColStuff()
{
m_colStuff.setRectangle(m_w, m_h);
}
void Actor::physic()
{
//setColStuff();
m_colStuff.followTheSprite(*this);
}
main.cpp
int main()
{
sf::RenderWindow window(sf::VideoMode(800, 600), "Platform");
std::list<Entity*>::iterator i;
Background BG;
Level1 FirstLev;
Actor Doodle;
while(window.isOpen())
{
sf::Event event;
if(window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
Doodle.inputEvts();
}
Doodle.act(Doodle.getAction());
Doodle.physic();
window.clear();
window.draw(BG.getSprite());
window.draw(Doodle.getSprite());
FirstLev.drawLevel(window);
window.display();
}
return 0;
}
It's really hard to tell from the bit of code that you posted, but if I had to guess I'd say it's probably related to this:
CollisionStuff getColStuff();
you're returning CollisionStuff by value, which means a new copy will be created by whoever is calling this. It'll have the same pointers that the original CollisionStuff object allocated, and it'll delete them when it goes out of scope, leaving the original one with dangling pointers.
You can try returning by reference or by pointer, but either way you should write a copy constructor and override the assignment operator for CollisionStuff (Rule of Three).
Another idea would be to use std::vector<sf::Vector2f> instead of allocating the sf::Vector2f array yourself.

Confused with variables in classes

I'm a bit confused with classes was hoping some one could explain.
I have a class I'm making to create buttons for a game menu. There are four variables:
int m_x
int m_y
int m_width
int m_height
I then want to use a render function in the class but Im not understanding how i use the 4 int variables in the class and pass it to the function in the class?
My class is like this:
class Button
{
private:
int m_x, m_y; // coordinates of upper left corner of control
int m_width, m_height; // size of control
public:
Button(int x, int y, int width, int height)
{
m_x = x;
m_y = y;
m_width = width;
m_height = height;
}
void Render(SDL_Surface *source,SDL_Surface *destination,int x, int y)
{
SDL_Rect offset;
offset.x = x;
offset.y = y;
SDL_BlitSurface( source, NULL, destination, &offset );
}
} //end class
Where i am confused is how the values created in public:Button is passed to void render I'm not fully sure I've got this right, if i have its pure luck so far because I'm still a little bit confused.
Maybe an example will help:
#include <iostream>
class Button
{
private:
int m_x, m_y; // coordinates of upper left corner of control
int m_width, m_height; // size of control
public:
Button(int x, int y, int width, int height) :
//This is initialization list syntax. The other way works,
//but is almost always inferior.
m_x(x), m_y(y), m_width(width), m_height(height)
{
}
void MemberFunction()
{
std::cout << m_x << '\n';
std::cout << m_y << '\n';
//etc... use all the members.
}
};
int main() {
//Construct a Button called `button`,
//passing 10,30,100,500 to the constructor
Button button(10,30,100,500);
//Call MemberFunction() on `button`.
//MemberFunction() implicitly has access
//to the m_x, m_y, m_width and m_height
//members of `button`.
button.MemberFunction();
}
You might want to spend some time learning C++ before getting too deep into a complex programming project.
To answer your question, The variables initialized in the constructor (Button) are part of the class instance. So they're available within any class method, including Render.