• Advertisement

Wierd bug

Recommended Posts

Hello, I'm having a rather strange bug. I'm making puzzle game.

When the game starts(PlayState) for the first time  pieces are indeed correctly placed, but after that sometimes they appear fine and most of the time only half of each piece is present ( I'm composing them out of 2 rectangles). The other parts appear at coordinates like this : Part2: X[1] : 842150923, Y[1]: 842150691. It happens even if I don' t use rand().

I'm using a state machine:

PlayState can go to:

    - pause state

PauseState can go to:

 - Resume

- Main Menu stateMain

MenuState can go to:

- PlayState

- Exit

I'm following a  book "SDL Game Development" by Shaun Mitchell (btw It's full of bugs).

bool PlayState::onEnter() {
  
    int left_x = 600 + (rand() % static_cast<int>(750 - 600 + 1));
    int left_y = 500 + (rand() % static_cast<int>(500 - 100 + 1));
    Vec2 dimension = Vec2(100, 200);
    int right_x = left_x + 100;
    int right_y = left_y;
    Vec2 dimension_2 = Vec2(100, 200);
    SDL_Color color1 = { 255, 0, 0, 0 };
    Piece* piece = new Piece(Vec2(left_x, left_y), Vec2(right_x, right_y), dimension, dimension_2, color1);
  // Piece 2
    int i_left_x = 600 + (rand() % static_cast<int>(750 - 600 + 1));
    int i_left_y = 500 + (rand() % static_cast<int>(500 - 100 + 1));
    Vec2 dimension_i1 = Vec2(100, 100);
    int i_right_x = i_left_x;
    int i_right_y = i_left_y + 100;
    Vec2 dimension_i2 = Vec2(100, 100);
    SDL_Color color3 = { 0, 0, 255, 0 };
    Piece* piece3 = new Piece(Vec2(i_left_x, i_left_y), Vec2(i_right_x, i_right_y), dimension_i1, dimension_i2, color3);
  // and so on until I have 7 pieces.


}
// ...
void PlayState::update() {
    if (InputHandler::Instance()->isKeyDown(SDL_SCANCODE_ESCAPE)) {
        Game::Instance()->getStateMachine()->pushState(new PauseState());
    }

   for (unsigned int i = 0; i < m_pieces.size(); i++){
           m_pieces[i]->update();
}

The issue occurs when I go from  MainMenuState to PlayState after PauseState.

I'll provide additional  info if needed. Thanks in advance.

Edited by Dzuvan
Misspelled words

Share this post


Link to post
Share on other sites
Advertisement

Well I'm using constructor like this:

    Piece(): 
        m_position(Vec2(0,0)),m_position2(Vec2(0,0)),
        m_dimension(Vec2(0, 0)), m_dimension2(Vec2(0,0)), 
        offset(Vec2(0,0)), offset2(Vec2(0,0)) {}

My c++ is quite bad so I'm 100% missing something.

Share this post


Link to post
Share on other sites

Are you cleaning up your heap allocations when changing states, or preserving them for later? That could be causing some sort of issue, but it's hard to tell with the limited code posted. Try posting the other two states too? Also, why are you static casting an int to an int?

Share this post


Link to post
Share on other sites

Code you posted seems fine at first sight, 842150923 is 0x3232340b in hex, which is not near any limit. Since it's not happening at first, I am going with accessing non-existing data (eg accessing a piece after it got deleted).

For example, in your m_pieces vector, do you remove anything from it? If you do, do you delete the data (not related to this bug, but important to do right)? Do you ensure you cannot access that old data any more?

As a test, you could fill all values of a piece with a known and unused value just before you remove it, and then remove the piece (eg in a destructor). Since those values are in removed data, you should never find them in your live data. If you find those values in your live data, you know what the problem is. Sadly, if you don't find those values, it does not mean you don't have this problem.

Code-wise, how you remove and add a piece to m_pieces could be interesting, along with how you decide which elements contain live data, although your PlayState::update suggests everything in the vector is live data.

 

You could consider posting the code eg at github or some other site, which works better for larger code bases.

 

Edit: 842150691 is 0x32323323, which also has lots of 2 and 3s. Maybe it's text? http://www.asciitable.com/

thus  0x32323323 -> 32 32 33 23 -> "223#"

           0x3232340b -> 32 32 34 0b -> "224." (0b is not a printable character)

So yeah, garbage data you're reading, likely from a previous program that used that memory

 

Edited by Alberth

Share this post


Link to post
Share on other sites
1 hour ago, cmac said:

Are you cleaning up your heap allocations when changing states, or preserving them for later? That could be causing some sort of issue, but it's hard to tell with the limited code posted. Try posting the other two states too? Also, why are you static casting an int to an int?

Well I'm calling clear on vector that holds data.

bool PlayState::onExit() {
    for (unsigned int i = 0; i < m_pieces.size(); i++) {
        m_pieces[i]->clean(); // doesn't do anything. It's empty void function 
        m_pieces[i]->setOffset(Vec2(0, 0));
    }
    m_pieces.clear();
    std::cout<<"Exiting playState\n"<<std::endl;
    return true;

  
 // Here is state machine I'm Using 
  #include "InputHandler.h"

void GameStateMachine::pushState(GameState* pState) {
    m_gameStates.push_back(pState);
    m_gameStates.back()->onEnter();
}

void GameStateMachine::popState() {
    if (!m_gameStates.empty()) {
        if (m_gameStates.back()->onExit()) {
            delete m_gameStates.back();
            m_gameStates.pop_back();
        }
    }
}

void GameStateMachine::changeState(GameState* pState) {
    if (!m_gameStates.empty()) {
        if (m_gameStates.back()->getStateID() == pState->getStateID()) {
            return;
        }
        if (m_gameStates.back()->getIsValid()) {
            m_gameStates.back()->setIsValid(false); // Mark the state as invalid
        }
    }
    
    m_gameStates.push_back(pState);
    m_gameStates.back()->onEnter();
}

void GameStateMachine::update(){
    if (!m_gameStates.empty()) {
          m_gameStates.back()->update();
    }
}
void GameStateMachine::render() {
    if (!m_gameStates.empty()) {
        m_gameStates.back()->render();
    }
}

void GameStateMachine::dequeState() {
    if (!m_gameStates.empty()) {
        // If the state is invalid we proceed to dequeue the state
        if (!m_gameStates[0]->getIsValid() && m_gameStates[0]->onExit()) {
            delete m_gameStates[0];
            m_gameStates.erase(m_gameStates.begin());

            // Reset the Input handler buttons state
            // This line is extremely important, fixes an issue with the "State traveling"
            // when a button is in the position of another button in another state
            // this will prevent the accident of traveling 2 states with 1 click.
            InputHandler::Instance()->reset();
        }
    }
}
// Here is the call from MainMenuState 
  void MainMenuState::s_menuToPlay() {
    std::cout << "Play button clicked\n"<<std::endl;
    Game::Instance()->getStateMachine()->changeState(new PlayState());
}

bool MainMenuState::onExit() {
    for (unsigned int i = 0; i < m_buttons.size(); i++) {
        m_buttons[i]->clean();
    }
    m_buttons.clear();
    TextureManager::Instance()->clearFromTextureMap("playbutton");
    TextureManager::Instance()->clearFromTextureMap("exitbutton");

    std::cout << "Exiting menu state\n"<<std::endl;
    return true;
}

As for the static cast, I saw post on stackoverflow, since I thought rand was causing the issue. I changed that part of code.

Share this post


Link to post
Share on other sites

Read up on memory management; clearing the vector causes the pointer to go out of scope, but the data is never deleted, resulting in a memory leak.

Overall though read Alberth's post in detail, seems like he nailed the problem down.

Share this post


Link to post
Share on other sites
1 hour ago, Alberth said:

Code you posted seems fine at first sight, 842150923 is 0x3232340b in hex, which is not near any limit. Since it's not happening at first, I am going with accessing non-existing data (eg accessing a piece after it got deleted).

For example, in your m_pieces vector, do you remove anything from it? If you do, do you delete the data (not related to this bug, but important to do right)? Do you ensure you cannot access that old data any more?

As a test, you could fill all values of a piece with a known and unused value just before you remove it, and then remove the piece (eg in a destructor). Since those values are in removed data, you should never find them in your live data. If you find those values in your live data, you know what the problem is. Sadly, if you don't find those values, it does not mean you don't have this problem.

Code-wise, how you remove and add a piece to m_pieces could be interesting, along with how you decide which elements contain live data, although your PlayState::update suggests everything in the vector is live data.

 

You could consider posting the code eg at github or some other site, which works better for larger code bases.

 

Edit: 842150691 is 0x32323323, which also has lots of 2 and 3s. Maybe it's text? http://www.asciitable.com/

thus  0x32323323 -> 32 32 33 23 -> "223#"

           0x3232340b -> 32 32 34 0b -> "224." (0b is not a printable character)

So yeah, garbage data you're reading, likely from a previous program that used that memory

 

I do have code on github(I've fucked up code so many times in the past xD ) : https://github.com/Dzuvan/Puzzle

Well I'm gonna try to test it the way you described, thanks.

Yeah everything in that vector si live data. I'm only handling pieces in PlayState.

Share this post


Link to post
Share on other sites

Hi guys, I managed to fix the problem.

State machine was the culprit here. Changing state from pause to main menu didn't remove play state from stack. Once i  poped the  state while going to main menu problem went away.

Thank you all.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


  • Advertisement
  • Advertisement
  • Popular Tags

  • Advertisement
  • Popular Now

  • Similar Content

    • By isu diss
      I'm trying to duplicate vertices using std::map to be used in a vertex buffer. I don't get the correct index buffer(myInds) or vertex buffer(myVerts). I can get the index array from FBX but it differs from what I get in the following std::map code. Any help is much appreciated.
      struct FBXVTX { XMFLOAT3 Position; XMFLOAT2 TextureCoord; XMFLOAT3 Normal; }; std::map< FBXVTX, int > myVertsMap; std::vector<FBXVTX> myVerts; std::vector<int> myInds; HRESULT FBXLoader::Open(HWND hWnd, char* Filename, bool UsePositionOnly) { HRESULT hr = S_OK; if (FBXM) { FBXIOS = FbxIOSettings::Create(FBXM, IOSROOT); FBXM->SetIOSettings(FBXIOS); FBXI = FbxImporter::Create(FBXM, ""); if (!(FBXI->Initialize(Filename, -1, FBXIOS))) { hr = E_FAIL; MessageBox(hWnd, (wchar_t*)FBXI->GetStatus().GetErrorString(), TEXT("ALM"), MB_OK); } FBXS = FbxScene::Create(FBXM, "REALMS"); if (!FBXS) { hr = E_FAIL; MessageBox(hWnd, TEXT("Failed to create the scene"), TEXT("ALM"), MB_OK); } if (!(FBXI->Import(FBXS))) { hr = E_FAIL; MessageBox(hWnd, TEXT("Failed to import fbx file content into the scene"), TEXT("ALM"), MB_OK); } FbxAxisSystem OurAxisSystem = FbxAxisSystem::DirectX; FbxAxisSystem SceneAxisSystem = FBXS->GetGlobalSettings().GetAxisSystem(); if(SceneAxisSystem != OurAxisSystem) { FbxAxisSystem::DirectX.ConvertScene(FBXS); } FbxSystemUnit SceneSystemUnit = FBXS->GetGlobalSettings().GetSystemUnit(); if( SceneSystemUnit.GetScaleFactor() != 1.0 ) { FbxSystemUnit::cm.ConvertScene( FBXS ); } if (FBXI) FBXI->Destroy(); FbxNode* MainNode = FBXS->GetRootNode(); int NumKids = MainNode->GetChildCount(); FbxNode* ChildNode = NULL; for (int i=0; i<NumKids; i++) { ChildNode = MainNode->GetChild(i); FbxNodeAttribute* NodeAttribute = ChildNode->GetNodeAttribute(); if (NodeAttribute->GetAttributeType() == FbxNodeAttribute::eMesh) { FbxMesh* Mesh = ChildNode->GetMesh(); if (UsePositionOnly) { NumVertices = Mesh->GetControlPointsCount();//number of vertices MyV = new XMFLOAT3[NumVertices]; for (DWORD j = 0; j < NumVertices; j++) { FbxVector4 Vertex = Mesh->GetControlPointAt(j);//Gets the control point at the specified index. MyV[j] = XMFLOAT3((float)Vertex.mData[0], (float)Vertex.mData[1], (float)Vertex.mData[2]); } NumIndices = Mesh->GetPolygonVertexCount();//number of indices MyI = (DWORD*)Mesh->GetPolygonVertices();//index array } else { FbxLayerElementArrayTemplate<FbxVector2>* uvVertices = NULL; Mesh->GetTextureUV(&uvVertices); int idx = 0; for (int i = 0; i < Mesh->GetPolygonCount(); i++)//polygon(=mostly triangle) count { for (int j = 0; j < Mesh->GetPolygonSize(i); j++)//retrieves number of vertices in a polygon { FBXVTX myVert; int p_index = 3*i+j; int t_index = Mesh->GetTextureUVIndex(i, j); FbxVector4 Vertex = Mesh->GetControlPointAt(p_index);//Gets the control point at the specified index. myVert.Position = XMFLOAT3((float)Vertex.mData[0], (float)Vertex.mData[1], (float)Vertex.mData[2]); FbxVector4 Normal; Mesh->GetPolygonVertexNormal(i, j, Normal); myVert.Normal = XMFLOAT3((float)Normal.mData[0], (float)Normal.mData[1], (float)Normal.mData[2]); FbxVector2 uv = uvVertices->GetAt(t_index); myVert.TextureCoord = XMFLOAT2((float)uv.mData[0], (float)uv.mData[1]); if ( myVertsMap.find( myVert ) != myVertsMap.end() ) myInds.push_back( myVertsMap[ myVert ]); else { myVertsMap.insert( std::pair<FBXVTX, int> (myVert, idx ) ); myVerts.push_back(myVert); myInds.push_back(idx); idx++; } } } } } } } else { hr = E_FAIL; MessageBox(hWnd, TEXT("Failed to create the FBX Manager"), TEXT("ALM"), MB_OK); } return hr; } bool operator < ( const FBXVTX &lValue, const FBXVTX &rValue) { if (lValue.Position.x != rValue.Position.x) return(lValue.Position.x < rValue.Position.x); if (lValue.Position.y != rValue.Position.y) return(lValue.Position.y < rValue.Position.y); if (lValue.Position.z != rValue.Position.z) return(lValue.Position.z < rValue.Position.z); if (lValue.TextureCoord.x != rValue.TextureCoord.x) return(lValue.TextureCoord.x < rValue.TextureCoord.x); if (lValue.TextureCoord.y != rValue.TextureCoord.y) return(lValue.TextureCoord.y < rValue.TextureCoord.y); if (lValue.Normal.x != rValue.Normal.x) return(lValue.Normal.x < rValue.Normal.x); if (lValue.Normal.y != rValue.Normal.y) return(lValue.Normal.y < rValue.Normal.y); return(lValue.Normal.z < rValue.Normal.z); }  
    • By Karol Plewa
      Hi, 
       
      I am working on a project where I'm trying to use Forward Plus Rendering on point lights. I have a simple reflective scene with many point lights moving around it. I am using effects file (.fx) to keep my shaders in one place. I am having a problem with Compute Shader code. I cannot get it to work properly and calculate the tiles and lighting properly. 
       
      Is there anyone that is wishing to help me set up my compute shader?
      Thank you in advance for any replies and interest!
    • By fishyperil
      I'm looking for some references that could help me learn how to program some really basic 2D enemy behaviours.
      I wasn't sure whether to post this here or in the AI section but I think it might be more suitable to be posted here since it has more to do with basic maths than any AI related algorithms.
      Could anyone help recommend some resources (books, posts, videos) that could help me understand how to properly implement the basics of enemy movement in 2d games ? So far I've only managed to get them to chase the player character and to stop moving on collision, but the movement is pretty unrealistic and once the collision occurs the enemies all "pile up" on the player character. I'm doing this in C++ so no guides that explain how to script this using an engine api please.
    • By LifeArtist
      Good Evening,
      I want to make a 2D game which involves displaying some debug information. Especially for collision, enemy sights and so on ...
      First of I was thinking about all those shapes which I need will need for debugging purposes: circles, rectangles, lines, polygons.
      I am really stucked right now because of the fundamental question:
      Where do I store my vertices positions for each line (object)? Currently I am not using a model matrix because I am using orthographic projection and set the final position within the VBO. That means that if I add a new line I would have to expand the "points" array and re-upload (recall glBufferData) it every time. The other method would be to use a model matrix and a fixed vbo for a line but it would be also messy to exactly create a line from (0,0) to (100,20) calculating the rotation and scale to make it fit.
      If I proceed with option 1 "updating the array each frame" I was thinking of having 4 draw calls every frame for the lines vao, polygons vao and so on. 
      In addition to that I am planning to use some sort of ECS based architecture. So the other question would be:
      Should I treat those debug objects as entities/components?
      For me it would make sense to treat them as entities but that's creates a new issue with the previous array approach because it would have for example a transform and render component. A special render component for debug objects (no texture etc) ... For me the transform component is also just a matrix but how would I then define a line?
      Treating them as components would'nt be a good idea in my eyes because then I would always need an entity. Well entity is just an id !? So maybe its a component?
      Regards,
      LifeArtist
    • By nickyc95
      Hi.
      I'm kind of late to this party but I thought I would ask anyway as I haven't found a concrete answer.
       
      When creating a game engine, when should you choose one methodology over another (more specifically OOP and DOD)? Which areas benefit from DOD? Which areas benefit from OOP? Do people typically mix multiple methodologies throughout a project? I.e. certain sub-systems created in one, and others in the another?  
      DOD - Data Oriented Design
      OOP - Object Oriented Design
       
      Pretty simple
      Thanks
  • Advertisement