Why are the contents of these pointers changing inside this Vector and throwing a read access violation exception? - c++

Basically, I am finishing a game engine, and one of the processes is to evaluate collision detection between colliders.
The problem is, is that the gameObjects/colliders I collect from the game map seems to completely change after several iterations of searching for collision detections.
Below shows how I obtained these colliders, I give the game map an empty vector called mapObjects so that it fills the vector with game objects
Game.cpp
vector<SimObject*> mapObjects;
currentMap = new GameMap("GameMap.txt", mapObjects, *texManager);
renderer->SetScreenProperties(16, currentMap->GetMapWidth(), currentMap->GetMapHeight());
for (int i = 0; i < mapObjects.size(); i++) {
AddNewObject(mapObjects[i]);
}
Then the map objects get processed through a function, which is put onto another vector and also dissected to place the collider and the rigid body into two other different vectors, allColliders and allBodies:
Game.cpp
void Game::AddNewObject(SimObject* object) {
newObjects.emplace_back(object);
physics->AddRigidBody(object);
if (object->GetCollider()) {
physics->AddCollider(object->GetCollider());
}
}
The way the game map obtains these objects is by evaluating the game map data, transforms these into Vector4 instances containing x, y, width and height, then is iterated and transformed into game objects for e.g. finding the walls:
GameMap.cpp
for (int i = 0; i < walls.size(); i++) {
Wall* wall = new Wall(walls[i]);
objects.emplace_back(wall);
}
Inside the wall constructor, this happens:
Wall::Wall(Vector4 vec) : StaticObject(vec)
which the following involves this basically:
StaticObject::StaticObject(Vector4 vec)
{
float midX = vec.x + ((vec.z - vec.x) / 2.0f);
float midY = vec.y + ((vec.w - vec.y) / 2.0f);
SetPosition(Vector2(midX, midY));
float halfW = midX - vec.x;
float halfH = midY - vec.y;
SetCollider(new CollisionVolume(this, Vector2(halfW, halfH)));
fixed = true;
}
Everything works fine at first, but after several iterations of this:
Game.cpp
void GameSimsPhysics::CollisionDetection(float dt) {
for (int i = 0; i < allColliders.size(); ++i) {
for (int j = i + 1; j < allColliders.size(); ++j) {
allColliders[i]->DetectCollision(*allColliders[j]);
}
}
}
A read access violation is thrown:
Unhandled exception thrown: read access violation.
this was 0xFFFFFFFFFFFFFFFF.
I had an investigate through the debugger, and it says that it is unable to read memory of the contents. However, if game objects were added within Game.cpp just after finding the map objects, their contents seem to be still in tact and unchanged:
player = new PlayerCharacter();
player->SetPosition(Vector2(100, 32));
player->SetCollider(new CollisionVolume(player, 10.0f));
AddNewObject(player);
I am really unsure and stuck at the moment, so I will appreciate any help! I have tried to keep it as simple as possible, but let me know if more information is needed.

Related

Why am I getting Undefined Behavior (EXC_BAD_ACCESS (code=1, address=0x1177c1530)) when I access a position of a matrix (opencv mat) on Xcode

I am trying to develop a c++ program with opencv library on Xcode 9.3, macOS 10.14, using clang. During weeks I've been trying to solve or understand why I am getting an undefined behavior error that sometimes makes my program crash and sometimes not.
I am reading a set of images from different cameras and storing them in a multidimensional array: silC[camera][image]. (images are well stored)
I get this error THREAD 1: EXC_BAD_ACCESS (code=1, address=0x1177c1530) when I do this: currentImage.at(x,y) even the values of currentImage are not the problem nor the image.
I post the code below if there's any chance someone could help me..
vector< vector<Mat> > silC(8,vector<Mat>()); // Store the pbm images separating from different cameras
* I read the images and store them in silC. *
for (int z=0; z < nz; z++) {
for (int y=0; y < ny; y++) {
for (int x=0; x < nx; x++) {
// Current voxel coordinates in the 3D space
float xcoord = x*voxelsize + Ox + voxelsize/2;
float ycoord = y*voxelsize + Oy + voxelsize/2;
float zcoord = z*voxelsize + Oz + voxelsize/2;
for (int camId=0; camId < matricesP.size(); camId++) {
imgId = 0;
currentImage = silC[camId][imgId];
int w = silC[camId][imgId].cols;
int h = silC[camId][imgId].rows;
// Project the voxel from the 3D space to the images
Mat P = matricesP[camId];
Mat projection = P*(Mat_<float>(4,1) << xcoord,ycoord,zcoord,1.0);
//We get the point in homog coord.
float xp = projection.at<float>(0);
float yp = projection.at<float>(1);
float zp = projection.at<float>(2);
// Get the cartesian coord
int xp2d = cvRound(xp/zp);
int yp2d = cvRound(yp/zp);
if(xp2d >= 0 && xp2d < w && yp2d >= 0 && yp2d < h){
// all values are correct! :/
// int value = silC[camId][imgId].at<float>(xp2d, yp2d); // undefined behaviour: crashes sometimes..
int value = currentImage.at<float>(xp2d, yp2d); // undefined behaviour also crashes sometimes..
if(value == 255){
cout << "Voxel okey \n";
}
}
}
}
}
}
EDIT:
The solution posted on comments below is that instead of currentImage.at(xp2d,yp2d) --> currentImage.at(yp2d,xp2d), as cv::Mat access requieres.
BUT, I tried to parallelize the for several times with openMP (#pragma omp parallel for) but it kept crashing. If someone is familiar with parallelize I'll appreciate any help.
the solution is what #rafix07 posted. Thank you very much guys, next time I'll try to focus more.

How to check whether an index in an array is empty

I'm making a small OpenGL program for my intro to C++ class in Uni. I have a program that is complete but I want to change it up a bit to make it more unique. I have a Cube class:
class Cube {
public:
Cube(Mesh* mesh, Texture2D* texture, float x, float y, float z);
~Cube();
void Draw();
void Update(float rSpeed);
Vector3 position;
private:
GLfloat rotationSpeed;
Vector3 rotationVector;
Mesh* _mesh;
Texture2D* _texture;
};
I then create an array of type Cube:
Cube* cubes[CUBE_AMOUNT];
I then fill each index of this array with data to draw the cube on screen later in the program:
for (int i = 0; i < CUBE_AMOUNT; i++) {
float x = ((rand() % 400) / 10.0f) - 20.0f;
float y = ((rand() % 200) / 10.0f) - 10.0f;
float z = -(rand() % 1000);
if (i % 2 == 1) {
cubes[i] = new Cube(cubeMesh, textureStars, x, y, z);
}
else {
cubes[i] = new Cube(cubeMesh, texturePenguins, x, y, z);
}
}
With this new thing I want to add to the program, I want to check whether an index of cubes[] has been filled with the data yet. However I keep getting exceptions when running. I have tried to check whether cubes[i] is equal to nullptr, and tried checking whether it is NULL too, but neither seem to match.
Sorry for any errors in terminology that I used. New to C++, and having come from only doing Python before this, it is confusing!
Solution:
When I create the array, I changed it to Cube* cubes[CUBE_AMOUNT] = { NULL }, and now when checking the array, cubes[i] == NULL!
If cubes is not a global variable, you can use:
Cube* cubes[CUBE_AMOUNT] = {};
to initialize all the elements to nullptr.
You can also use:
std::vector<std::unique_ptr<Cube>> cubes(CUBE_AMOUNT);
to remove the burden of having to deallocate dynamic memory in your code.
In either case, can use:
if ( cubes[index] )
{
// Got a valid pointer. Use it.
}
Your cubes variable is not automatically initialized with null_ptr's. Until you either fill it with null_ptr's or good pointers it initially points to random garbage.
I think this would work
//This bit should check if theres anything stored currently.
cout << "\nWhich Slot would you like to store the informaton in ?(1-10)";
cin >> i;
i--;
if (information[i] != NULL){
// Already written
cout << "THERES SOMETHING HERE";
}
else{
cout << "\nEMPTY!!!!!!!!!";
}

C++ code for Microsoft Kinect - trying to dynamically allocate array of target positions

So I'm trying to modify the Kinect BodyBasicsD2D code so that a fixed number of "target positions" appear on the screen (as ellipses) for the user to move his hand toward. I'm having trouble creating the initial target positions.
This is my code in the header file for the allocation of the array of target positions (these are a public field of the CBodyBasics class, already built into the original BodyToBasics program):
D2D1_POINT_2F* targetPositions = NULL;
int numTargets = 3;
Then I have a function "GenerateTargetPositions" which is supposed to generate 3, in this case, target positions to be passed into the "DrawTargetPositions" function.
void CBodyBasics::GenerateTargetPositions(D2D1_POINT_2F * targetPositions, int numTargets)
{
targetPositions = new D2D1_POINT_2F[numTargets];
RECT rct;
GetClientRect(GetDlgItem(m_hWnd, IDC_VIDEOVIEW), &rct);
int width = rct.right;
int height = rct.bottom;
FLOAT x;
FLOAT y;
D2D1_POINT_2F tempPoint;
for (int i = 0; i < numTargets; i++) {
x = 1.0f*i*width / numTargets;
y = 1.0f*i*height / numTargets;
tempPoint = D2D1::Point2F(x, y);
targetPositions[i] = tempPoint;
}
}
My DrawTargetPositions function is:
void CBodyBasics::DrawTargetPositions(D2D1_POINT_2F * targetPositions, int numTargets)
{
D2D1_ELLIPSE ellipse;
for (int i = 0; i < numTargets; i++)
{
ellipse = D2D1::Ellipse(targetPositions[i], 50.f, 50.f);
m_pRenderTarget->FillEllipse(ellipse, m_pSilverBrush);
}
}
When I try to run my code, I get the error that both "targetPositions" and "targetPositions[i]" is NULL (and thus my GenerateTargetPositions function must not be working properly). I believe that targetPositions[i] is a struct (a point with x and y values) so I am wondering if this may be the reason for my errors.
I call GenerateTargetPositions and DrawTargetPositions before the main "while" loop in my code so that each function is not being called on each iteration (there are many iterations of through the while loop because this is an interactive Microsoft Kinect, recording one's movements).
Any suggestions and advice would be greatly appreciated. Thanks so much!

Tile mapping error

I am still learning SFML and C++ so please understand that I'm still at the basic level.
This is my first time using this site so IDK if I'm doing this right.
I want to make a function, set, that will allow me to pass a 2d array as an argument and place a tile down whenever there is a 1 in the array. So I can draw maps and things using a matrix. ww is the window width and wh is the window height. In main I made a for loop that would go through tiles and draw them to the window. But when I run this it gives me the error: Segmentation Fault (core dumped) "Error: 139". Is there a better way of doing this and what am I doing wrong?
Thank you.
struct field
{
int rectsizex;
int rectsizey;
RectangleShape * tiles;
field (int s)
{
rectsizex = ww / s;
rectsizey = wh / s;
tiles = new RectangleShape[rectsizex * rectsizey];
}
~field()
{
delete tiles;
}
RectangleShape * set(int ** matr)
{
Vector2f size((ww / rectsizex), (wh / rectsizey));
int posx = ww / rectsizex;
int posy = wh / rectsizey;
for(int x = 0; x<rectsizex; x++)
{
for(int y = 0; y<rectsizey; y++)
{
int i = ((x*rectsizey)+1)+y;
tiles[i].setSize(size);
if(matr[x][y] == 1)
{
tiles[i].setFillColor(Color::Black);
}
else
{
tiles[i].setFillColor(Color::White);
}
tiles[i].setPosition(x * posx, y * posy);
}
}
return tiles;
}
};
Find out what values you are getting for i:
int i = ((x*rectsizey)+1)+y;
This value is definitely outside of your array bounds, hence the error. Use a debugger, or put some print statements after you get the i value.

Interfering Vector in glBegin()

I am trying to implement code for an assignment to render skeleton and mesh animations. In my glBegin(GL_TRIANGLES) section, I have some vectors that appear to be interfering with my information when it shouldn't.
glBegin(GL_TRIANGLES);
for (int i = 0; i < mesh->nfaces.size(); i += 1)
for (int k = 0; k < 3; k += 1) {
int j = k;//2 - k;
glm::vec4 myPointPrime;
myPointPrime.w = 1;
myPoint.x = ecks = mesh->vertex[mesh->faces[i][j]][0];
myPoint.y = why = mesh->vertex[mesh->faces[i][j]][1];
myPoint.z = zed = mesh->vertex[mesh->faces[i][j]][2];
// Stuff vvvv THIS CAUSES PROBLEMS
for (int t = 0; t < mySkeleton->vertex.at(i).size(); t++) {
myPointPrime += mySkeleton->vertex[i][j] * MyXformations * myPoint;
}
glNormal3f(mesh->normal[mesh->nfaces[i][j]][0],
mesh->normal[mesh->nfaces[i][j]][1],
mesh->normal[mesh->nfaces[i][j]][2]);
glVertex3f(mesh->vertex[mesh->faces[i][j]][0],
mesh->vertex[mesh->faces[i][j]][1],
mesh->vertex[mesh->faces[i][j]][2]);
// glVertex3f(myPointPrime.x, myPointPrime.y, myPointPrime.z);
// glVertex3f(myPoint.x, myPoint.y, myPoint.z);
}
glEnd();
The myPointPrime += ... code is doing something weird to my Vertex calls, the scene won't render unless I comment out that for loop.
If I comment out the loop, then the scene renders, but I think I kinda need the loop if animating something like 16,000 vertexes is going to have any performance at all.
Is having that there kind of like having it automatically multiply with the glVertex calls?
Edit:
Below is another version of the code I hope should be more clear, instead of calculating the points in the actual drawing code I change the whole mesh to supposedly follow the skeleton each frame, but nothing is rendered.
for (int vertex_i = 0; vertex_i < mesh->nfaces.size(); vertex_i++) {
for (int k = 0; k < 3; k += 1) {
int j = k;//2 - k;
pointp.x = 0;
pointp.y = 0;
pointp.z = 0;
for (int t = 0; t < mySkeleton->vertex.at(vertex_i).size(); t++) {
point.x = mesh->vertex[mesh->faces[vertex_i][j]][0];
point.y = mesh->vertex[mesh->faces[vertex_i][j]][1];
point.z = mesh->vertex[mesh->faces[vertex_i][j]][2];
//glPushMatrix();
pointp += mySkeleton->vertex[vertex_i][t] * myTranslationMatrix * myRotationMatrix * point;
cout << "PointP X: " << pointp.x << " PointP Y: " << pointp.y << " PointP Z: " << pointp.z << endl;
mesh->vertex[mesh->faces[vertex_i][j]][0] = pointp.x;
mesh->vertex[mesh->faces[vertex_i][j]][1] = pointp.y;
mesh->vertex[mesh->faces[vertex_i][j]][2] = pointp.z;
//myPointPrime += MyXformations * myPoint;
}
}
}
My assumption is that maybe the calculations for pointp isn't doing what I think its doing?
mySkeleton->vertex[vertex_i][t] is a vector from my 'skeleton' class, it holds all of the weights for every vertex, there are 17 weights per vertex.
"MyXformations" is a 4x4 matrix passed from my skeleton animation function that holds the last known key frame and this is applied to the vertexes.
point is the current point in the vertex.
Your loop variable is t. However, you refer to j in the loop. Looks to me like your loop might simply be crashing for larger values of j.
You're not using t inside the for loop. Is this expected?
mySkeleton->vertex[i][j] looks like it's out of bounds since j should be for mesh->faces/mesh->nfaces.
Also you can use glNormal3fv and glVertex3fv with arrays.
With out of bounds memory operations you can get all sorts of weird stuff happening, although I can't see any out of bound writes. Your * operators don't modify the objects do they?
If you're worried about performance. You shouldn't be using immediate mode. Instead, put all your data on the GPU with buffer objects (including join/bone transformations) and animate on the fly in the vertex shader.
This is from a few years ago, but worth a read: Animated Crowd Rendering.