Why the rendered squares duplicate? - c++

My problem is that when i run programm it runs normally for around 10-20 seconds, and then it glitch out. You can see further what's happening on the video.
https://youtu.be/YOlhjQFTzZc
This error is hunting me for over a month, First i thought this was some mistake in making shorter Render function. But not.
You can see it here.
void Render(char * image_place, int object_x, int object_y)
{
SDL_Surface * object_image = IMG_Load(image_place);
SDL_Rect object_position;
object_position.x=object_x;
object_position.y=object_y;
SDL_BlitSurface(object_image, NULL, ekran, &object_position);
}
But when i started "researching" on this topic more, i discovered that it happen even without using this function!
Here is code from the video:
#include <iostream>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_mixer.h>
#include <SDL2/SDL_ttf.h>
#include <windows.h>
#include <time.h>
using namespace std;
//SDL
SDL_Window * okno;
SDL_Surface * ekran;
SDL_Rect pozycja_obramowki;
SDL_Event zdarzenie;
SDL_Rect tlo_pos;
//zmienne
int x_obraz=0;
int y_obraz=0;
int main(int argc, char*args[])
{
SDL_Init(SDL_INIT_EVERYTHING);
okno = SDL_CreateWindow("LevelEditor",SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED, 1280, 720, NULL);
ekran = SDL_GetWindowSurface(okno);
while(true)
{
{//render
SDL_Surface * tlo = IMG_Load("biel.png");
tlo_pos.x=0;
tlo_pos.y=0;
SDL_BlitSurface(tlo,NULL, ekran, &tlo_pos);
SDL_Surface * obramowka = IMG_Load("obramowka.png");
pozycja_obramowki.x=x_obraz;
pozycja_obramowki.y=y_obraz;
SDL_BlitSurface(obramowka,NULL, ekran, &pozycja_obramowki);
}
{//zdarzenia
if(SDL_PollEvent(&zdarzenie))
{
if(zdarzenie.type==SDL_QUIT)
{
return 0;
}
}
}
{//sterowanie
if(GetAsyncKeyState(VK_RIGHT)) {x_obraz=x_obraz+5;}
if(GetAsyncKeyState(VK_LEFT)) {x_obraz=x_obraz-5;}
if(GetAsyncKeyState(VK_UP)) {y_obraz=y_obraz-5;}
if(GetAsyncKeyState(VK_DOWN)) {y_obraz=y_obraz+5;}
}
{//fps end & odswiezanie ekranu
SDL_UpdateWindowSurface(okno);
}
}
}
If i wrote something wrong or explained anything wrong, feel free to comment on this post. Any help will be useful, thanks ; )

You shouldn't call IMG_Load repeatedly. (I suspect that you're running out of memory pretty quickly.)
Load all images at startup and store pointers to the resulting surfaces.
// Moved out of the loop
SDL_Surface * tlo = IMG_Load("biel.png");
SDL_Surface * obramowka = IMG_Load("obramowka.png");
while(true)
{
// As before, but without declaring the variables mentioned above.
}

Related

How to tell VTK pipeline to use new vtkPolyData updated via TimerEvent?

Intention
I wrote a VTK application that generates a spiral using vtkPoints > vtkPolyLine > vtkPolyData > vtkPolyDataMapper and displays it. This works fine, if done static at the initialization of the program.
Now, I want to add new data points dynamically. The intention is to visualize measurements in real time, so new data will be added in certain intervals.
Issues
Currently, I just implemented a TimerEvent to update the vtkPoints and vtkPolyLine. But, the program just shows the static data generated before the vtkRenderWindowInteractor was started. I also tried to use "Modified()" and "Update()" calls to nearly all objects, tried to remove, regenerate and add a new actor to the renderer -- but without success! I added my C++ code below...
Related-Questions
The following mailing list question is about this issues, but the solution given doen't work for me:
http://public.kitware.com/pipermail/vtkusers/2006-November/038377.html
The following question seems to be related, but there are no useful answers:
VTK: update data points in renderWindow at every simulation timestep
Questions
How to tell VTK that the vtkPolyData object has changed?
Which of the VTK UsersGuide should I probably have a closer look at?
Details / Source Code
I'm using Visual Studio Community 2017 and VTK 8.0.0, both compiled as Win32 target.
#include <vtkAutoInit.h>
VTK_MODULE_INIT(vtkRenderingOpenGL2);
VTK_MODULE_INIT(vtkRenderingContextOpenGL2);
VTK_MODULE_INIT(vtkRenderingVolumeOpenGL2);
VTK_MODULE_INIT(vtkInteractionStyle);
VTK_MODULE_INIT(vtkRenderingFreeType);
#include <vtkSmartPointer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderer.h>
#include <vtkConeSource.h>
#include <vtkPolyDataMapper.h>
#include <vtkActor.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkProperty.h>
#include <vtkPoints.h>
#include <vtkPolyLine.h>
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
vtkSmartPointer<vtkPolyLine> polyLine = vtkSmartPointer<vtkPolyLine>::New();
int numOfPoints = 0;
double t = 0;
void NextPoint() {
double x = t * cos(t);
double y = t * sin(t);
points->InsertNextPoint(x, y, t);
polyLine->GetPointIds()->InsertNextId(numOfPoints);
numOfPoints++;
t += 0.1;
}
vtkSmartPointer<vtkPolyData> generateEllipse() {
// Add some points so we actually see something at all...
for (int i = 0; i < 100; ++i) {
NextPoint();
}
vtkSmartPointer<vtkCellArray> cells = vtkSmartPointer<vtkCellArray>::New();
cells->InsertNextCell(polyLine);
vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New();
polyData->SetPoints(points);
polyData->SetLines(cells);
return polyData;
}
class vtkTimerCallback : public vtkCommand
{
public:
static vtkTimerCallback *New()
{
vtkTimerCallback *cb = new vtkTimerCallback;
cb->TimerCount = 0;
return cb;
}
virtual void Execute(vtkObject *vtkNotUsed(caller), unsigned long eventId,
void *vtkNotUsed(callData))
{
if (vtkCommand::TimerEvent == eventId)
{
NextPoint(); // Add another point to polyData
++this->TimerCount;
cout << this->TimerCount << endl;
}
}
private:
int TimerCount;
};
int main(int argc, char** argv) {
vtkSmartPointer<vtkRenderWindow> renderWindow =
vtkSmartPointer<vtkRenderWindow>::New();
vtkSmartPointer<vtkRenderWindowInteractor> rwi = vtkSmartPointer<vtkRenderWindowInteractor>::New();
rwi->SetRenderWindow(renderWindow);
vtkSmartPointer<vtkPolyData> data = generateEllipse();
vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputData(data);
vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper);
actor->GetProperty()->SetDiffuseColor(255, 255, 0);
vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New();
renderWindow->AddRenderer(renderer);
renderer->AddActor(actor);
renderer->ResetCamera();
renderWindow->Render();
// Add Timer Event...
rwi->Initialize();
vtkSmartPointer<vtkTimerCallback> cb = vtkSmartPointer<vtkTimerCallback>::New();
rwi->AddObserver(vtkCommand::TimerEvent, cb);
int timerId = rwi->CreateRepeatingTimer(100); // every 100ms
std::cout << "timerId: " << timerId << std::endl;
// Start Displaying...
rwi->Start();
return 0;
}
the problem is that the cells are not stored by pointer - when you call cells->InsertNextCell(polyLine); the data is copied, not pointed to, in order to create an efficient storage of the cells in an array (the whole implementation is actually in the header of vtkCellArray so you can check it out). So then when you update polyLine, it has no effect in the polydata, because the polydata have their own copy that you did not update. The following code works for me (you have to expose the polydata and the cellArray):
virtual void Execute(vtkObject *vtkNotUsed(caller), unsigned long eventId,
void *vtkNotUsed(callData))
{
if (vtkCommand::TimerEvent == eventId)
{
NextPoint(); // Add another point to polyData
cells->Initialize(); // reset the cells to remove the old spiral
cells->InsertNextCell(polyLine); // re-insert the updated spiral
cells->Modified(); // required to update
data->Modified(); // required to update
++this->TimerCount;
cout << polyLine->GetNumberOfPoints() << endl;
renderWindow->Render(); // refresh the render window after each update
}
}
Yesterday I worked out an alternative solution using a vtkProgrammableDataObjectSource as DataSource. Tomj's solution is the more direct and simple solution... However, there is no C++ Example Code at vtk.org that explains how to use vtkProgrammableDataObjectSource and I had to work it out by trial and error. So I'll post it here, as it might help others:
#include <vtkAutoInit.h>
VTK_MODULE_INIT(vtkRenderingOpenGL2);
VTK_MODULE_INIT(vtkRenderingContextOpenGL2);
VTK_MODULE_INIT(vtkRenderingVolumeOpenGL2);
VTK_MODULE_INIT(vtkInteractionStyle);
VTK_MODULE_INIT(vtkRenderingFreeType);
#include <vtkSmartPointer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderer.h>
#include <vtkConeSource.h>
#include <vtkPolyDataMapper.h>
#include <vtkActor.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkProperty.h>
#include <vtkPoints.h>
#include <vtkPolyLine.h>
#include <vtkProgrammableFilter.h>
#include <vtkCallbackCommand.h>
#include <vtkPolyDataStreamer.h>
#include <vtkProgrammableDataObjectSource.h>
vtkSmartPointer<vtkProgrammableDataObjectSource> pDOS = vtkSmartPointer<vtkProgrammableDataObjectSource>::New();
vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
vtkSmartPointer<vtkPolyLine> polyLine = vtkSmartPointer<vtkPolyLine>::New();
int numOfPoints = 0;
double t = 0;
void NextPoint() {
double x = t * cos(t);
double y = t * sin(t);
points->InsertNextPoint(x, y, t);
polyLine->GetPointIds()->InsertNextId(numOfPoints);
numOfPoints++;
t += 0.1;
}
void generateEllipse(void *caller) {
vtkProgrammableDataObjectSource *pDOS = vtkProgrammableDataObjectSource::SafeDownCast((vtkObjectBase*)caller);
vtkSmartPointer<vtkCellArray> cells = vtkSmartPointer<vtkCellArray>::New();
cells->InsertNextCell(polyLine);
vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New();
polyData->SetPoints(points);
polyData->SetLines(cells);
pDOS->SetOutput(polyData);
}
int counter2 = 0;
void TimerCallbackFunction(vtkObject* caller, long unsigned int vtkNotUsed(eventId), void* clientData, void* vtkNotUsed(callData)) {
cout << "timer callback: " << counter2 << endl;
// To avoid globals we can implement this later...
// vtkSmartPointer<vtkProgrammableDataObjectSource> pDOS =
// static_cast<vtkProgrammableDataObjectSource*>(clientData);
vtkRenderWindowInteractor *rwi =
static_cast<vtkRenderWindowInteractor*>(caller);
NextPoint();
pDOS->Modified();
rwi->Render();
renderer->ResetCamera(); // Optional: Reposition Camera, so it displays the whole object
counter2++;
}
int main(int argc, char** argv) {
vtkSmartPointer<vtkRenderWindow> renderWindow =
vtkSmartPointer<vtkRenderWindow>::New();
vtkSmartPointer<vtkRenderWindowInteractor> rwi = vtkSmartPointer<vtkRenderWindowInteractor>::New();
rwi->SetRenderWindow(renderWindow);
pDOS->SetExecuteMethod(&generateEllipse, pDOS);
vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputConnection(pDOS->GetOutputPort());
vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper);
actor->GetProperty()->SetDiffuseColor(255, 255, 0);
renderWindow->AddRenderer(renderer);
renderer->AddActor(actor);
renderer->ResetCamera();
renderWindow->Render();
// Add Timer Event...
vtkSmartPointer<vtkCallbackCommand> timerCallback = vtkSmartPointer<vtkCallbackCommand>::New();
timerCallback->SetCallback(TimerCallbackFunction);
rwi->Initialize();
rwi->CreateRepeatingTimer(100);
rwi->AddObserver(vtkCommand::TimerEvent, timerCallback);
// Start Displaying...
rwi->Start();
return 0;
}

C++ SFML sprite not showing/working

I am trying to make a program so that a red block falls from the top of the screen and the player has to avoid it. When I run the program I can see and move the player(paddle) but I can't see the enemy or "thing" sprite. Please help me because I have tried everything with the code and it still doesn't work :/
things.h
#include <SFML/Graphics.hpp>
#include <iostream>
using namespace sf;
using namespace std;
#pragma once
class Thing
{
public:
void thingspawn(RenderWindow &gameDisplay, int &enemystartx, int &enemystarty, int &enemywidth, int &enemyheight, int &blockcolor)
{
RectangleShape thing(Vector2f(enemywidth, enemyheight));
thing.setFillColor(Color(blockcolor));
thing.setPosition(enemystartx, enemystarty);
gameDisplay.clear();
gameDisplay.draw(thing);
}
};
main.cpp
#include <iostream>
#include <SFML/Graphics.hpp>
#include "things.h"
using namespace std;
using namespace sf;
int main()
{
RenderWindow gameDisplay(VideoMode(1366, 768), "Game", Style::Fullscreen);
gameDisplay.setMouseCursorVisible(false);
gameDisplay.clear();
int enemystarty = -200;
int enemystartx = 300;
int enemyheight = 100;
int enemywidth = 100;
int enemyspeed = 0.3f;
int enemycount = 1;
int dodged = 0;
int blockcolor = (255, 0, 0);
RectangleShape player(Vector2f(300, 30));
player.setFillColor(Color(0, 0, 255));
player.setPosition(400, 728);
while (gameDisplay.isOpen())
{
Event evnt;
while (gameDisplay.pollEvent(evnt))
{
switch (evnt.type)
{
case Event::Closed:
gameDisplay.close();
case Event::KeyPressed:
if (Keyboard::isKeyPressed(Keyboard::Q))
gameDisplay.close();
}
}
if (Keyboard::isKeyPressed(Keyboard::Right))
if (player.getPosition().x < 1000)
player.move(0.2f, 0.0f);
if (Keyboard::isKeyPressed(Keyboard::Left))
if (player.getPosition().x > 50)
player.move(-0.2f, 0.0f);
Thing thingobject;
thingobject.thingspawn(gameDisplay, enemystartx, enemystarty, enemywidth, enemyheight, blockcolor);
enemystarty += enemyspeed;
gameDisplay.draw(player);
gameDisplay.display();
}
}
The problem is that you create RectangleShape thing in function Thing::thingspawn(...) and it is destroyed after it ends.
Try to put declaration of it as member of the Thing class
The thing is rendering correctly but in just a bad habit way. like what capi1500 said,
But the real problem is that int blockcolor = (255, 0, 0); results a black color when you pass it to the sf::Color. you wont see a black drawing in a black canvas right?
You can see here on how to construct a color from an integer: How to pack ARGB to one integer uniquely?
for now change the color of the thing using the predefined colors of sf::Color like sf::Color::Green or pass each component using the another constructor Color (Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha=255)
SFML's sf::Color's documentation: http://www.sfml-dev.org/documentation/2.4.2/classsf_1_1Color.php

White gaussian noise addition using Qt

I looked out in the internet as well as I looked in here (stackoverflow) and could not find a good answer on how to implement white gaussian noise addition into my qimage object. or if there is an existing function which I can use?
any suggestions?
Thx in advance
The following code helped me alot:
#include <stdlib.h>
#include <math.h>
#include <time.h>
float gauss_rand(float mean,float stdev)
{
int i;
const int ORDER=2*12; /* 12,24,36 etc. due to del^2/12 */
const double dev_norm=1.4142136; /* sqrt(ORDER/12) */
double rndno;
rndno=-(ORDER>>1);
for(i=0;i<ORDER;i++) {
rndno+=(double)(rand()/(RAND_MAX+1.0));
}
rndno*=stdev/dev_norm;
rndno+=mean;
return((float)rndno);
}
void add_gaussian_noise(float **orig,int Ni,int Nj,float **noisy,float mean,float stdev)
{
int i,j;
static int kilroy=0;
unsigned int seed;
if(!kilroy) {
kilroy=1;
seed=(unsigned)time( NULL );
// uncomment for the same noise process
// seed=0;
srand(seed);
}
for(i=0;i<Ni;i++)
for(j=0;j<Nj;j++)
noisy[i][j]=orig[i][j]+gauss_rand(mean,stdev);
}

vector, sfml and "the value of esp was not properly saved across the function call" error

I have a struct "Layer" and class "LayerHandler". Layer consists only a texture, sprite and two constructors - one default and one with a reference parameter. LayerHandler class is a class that handles the drawing of all the layers we have. I add layers to this class and later I use win.draw(layerhandler_object) to draw everything. LayerHandler inherits from Drawable to do so and it overrides virtual void draw().
LayerHandler.h:
#ifndef LAYERHANDLER_H
#define LAYERHANDLER_H
#include <vector>
#include <SFML\Graphics.hpp>
using namespace std;
using namespace sf;
struct Layer {
Texture tex;
Sprite spr;
Layer() { }
Layer(Layer& l) {
tex = l.tex;
spr = l.spr;
}
};
class LayerHandler : public Drawable {
private:
vector<Layer*> layers;
virtual void draw(RenderTarget& target, RenderStates states) const {
for (int i=0; i<layers.size(); i++)
target.draw(layers[i]->spr, states);
}
public:
LayerHandler();
~LayerHandler();
void Add(Layer& layer);
};
#endif
LayerHandler.cpp:
#include "LayerHandler.h"
LayerHandler::LayerHandler() {
}
LayerHandler::~LayerHandler() {
}
void LayerHandler::Add(Layer& layer) {
layers.push_back(new Layer(layer));
}
and main.cpp:
#include <iostream>
#include <SFML\Graphics.hpp>
#include "LayerHandler.h"
using namespace std;
using namespace sf;
int main() {
RenderWindow win(VideoMode(800, 600), "Raven", Style::Default);
win.setFramerateLimit(60);
win.setVerticalSyncEnabled(true);
win.setMouseCursorVisible(false);
LayerHandler lhandler;
Layer back;
back.tex.loadFromFile("bao/gfx/back.png");
back.spr.setTexture(back.tex);
back.spr.setPosition(0, 50);
lhandler.Add(back);
Event evt;
float dt = 0.f;
Clock clock;
float dwticks = clock.getElapsedTime().asMilliseconds();
float dwnewticks = 0.f;
while (win.isOpen()) {
if (win.pollEvent(evt)) {
if (Keyboard::isKeyPressed(Keyboard::Key::Escape)) {
win.close();
}
} else {
dwnewticks = clock.getElapsedTime().asMilliseconds();
dt = dwnewticks > dwticks ? (dwnewticks - dwticks) / 4000.f : 0.f;
dwticks = dwnewticks;
win.clear();
win.draw(lhandler);
win.display();
}
}
return 0;
}
I think it's not complicated and that I did everything ok, but I get this "The value of ESP was not properly saved across the function call" error. I have no idea why I get this error. I know that it may be caused by mismatched calling conventions, but I don't see anything like that in my code... I've got to say that this is the first time ever I got this error and I'm completely out of ideas how to deal with it. Any help?
Don't know why, but the problem was with SFML libraries. Here I'm using version 2.2 for 32-bit apps. I downloaded version 2.3 32-bit and compiled my app with the new 2.3 libraries and now it works perfect.

C++ Variable not being instantiated properly

Sprite1 *test = new Sprite1(450, 450, "enemy.bmp", *screen);
test->DrawJon();
SDL_Delay(1000);
test->MoveJon(20,20);
I am getting a runtime error on line #2. It says access violation at 0x0
Sprite1 is a class I have defined and DrawJon() and MoneJon() in the class. This syntax is ok with the compiler but fails in runtime.
Sprite1.cpp
#include "Sprite1.h"
Sprite1::Sprite1(int posX, int posY, std::string imagePath, SDL_Surface screen) : PosX(posX), PosY(posY), ImagePath(imagePath), Screen(screen)
{
void DrawSprite1Jon( int x, int y, SDL_Surface *sprite, SDL_Surface *screen );
void DrawJon();
void MoveJon(int xDist, int yDist);
}
void Sprite1::DrawSprite1Jon( int x, int y, SDL_Surface *sprite, SDL_Surface *screen )
{
//Make a temporary rectangle to hold the offsets
SDL_Rect offset;
//Give the offsets to the rectangle
offset.x = x;
offset.y = y;
//Blit the surface
SDL_BlitSurface( sprite, NULL, screen, &offset );
SDL_UpdateRect(screen, 0, 0, 0, 0);
}
void Sprite1::DrawJon()
{
#pragma region Char to String Conversion
string ImagePath;
char * writable = new char[ImagePath.size() + 1];
copy(ImagePath.begin(), ImagePath.end(), writable);
writable[ImagePath.size()] = '\0';
#pragma endregion
temp = SDL_LoadBMP(writable);
sprite = SDL_DisplayFormat(temp);
SDL_FreeSurface(temp);
// free the string after using it
delete[] writable;
DrawSprite1Jon(PosX, PosY, sprite, screen);
}
Sprite1.h
#include <string>
#include <SDL.h>
#include "Functions.h"
using namespace std;
class Sprite1
{
private:
int PosX;
int PosY;
int xDist;
int yDist;
string ImagePath;
SDL_Surface Screen;
SDL_Surface *temp, *sprite, *screen;
public:
Sprite1(int PosX, int PosY, string ImagePath, SDL_Surface Screen );
void DrawSprite1Jon( int x, int y, SDL_Surface *sprite, SDL_Surface *screen);
void DrawJon();
void MoveJon(int xDist, int yDist);
};
EDIT:
upon further investigation, it is this line
DrawSprite1Jon(PosX, PosY, sprite, screen);
That is failing in the DrawJon()
At least this piece of your code is broken:
string ImagePath;
char * writable = new char[ImagePath.size() + 1];
copy(ImagePath.begin(), ImagePath.end(), writable);
writable[ImagePath.size()] = '\0';
You are creating local ImagePath variable, not using the class member variable. The local variable shadows the member variable. Remove the local variable (first line in above snippet).
Also, you can probably (I'm not very familiar with SDL) do the loading simply like this:
temp = SDL_LoadBMP(ImagePath.c_str());
Then, just guessing, but image loading might be failing, and that function returns NULL pointer. So check return value and then check the error (either there is some SDL error function you can call, or you need to check standard errno global variable.
Further suggestion: turn on compiler warnings (for gcc: -W -Wall) and learn to understand (copying the warning to google is a good start) and then fix the warnings. Most of the time they are real bugs (hence the warning!) and even when they are not, fixing the warning will make your code better.
I is apparent that you've just began to program in C++, maybe you have a javascript background, therefore you've tried to put function declarations into the constructor. It is a wrong idea here. (#pragma's usually have some explicit meaning, you also misuse them here. see eg. #pragma GCC poison)
I see a lot of confusion in this code.
I suggest, you grab a great quality beginner C++ book, before going ahead with this piece of code. At this point I see no reason trying to hammer-out something reasonable from this code.
There were some problems with my implementation but in the end I had to build in release mode rather than debug mode.