Why is the color in the cube being weirdly swapped? I am implementing a trackball, i.e. a camera orbiting about a fixed point, in my case the origin. When I do left click with the mouse and start moving it, I compute delta values for the angles of a sphere centered at the origin given the displacement in x and y directions of the mouse. My implementation is as follows

void SimplePerspectiveCamera::
mouseMove(const double&amp; mouseX, const double&amp; mouseY)
{
    if(m_setPan)
    {
        float sensitivity = 0.0075f;
        float newX = (mouseX - m_prevX) * sensitivity;
        float newY = (mouseY - m_prevY) * sensitivity;
        // TODO: Understand if it is necessary to reset the up vector to (0,1,0)
        m_up = Vector(0.0f, 1.0f, 0.0f);
        setLookAt(m_lookAt + Vector(-newX, newY, 0.0f));
        setPosition(m_position + Vector(-newX, newY, 0.0f));
        m_prevX = mouseX;
        m_prevY = mouseY;
    }
    if(m_setRotate)
    {
        float sensitivity = 0.005f;
        float newPhi = (mouseX - m_prevX) * sensitivity;
        float newTheta = (mouseY - m_prevY) * sensitivity;
        // Transform to spherical coordinates to use mouse move as deltas for
        // the angles.
        float r = m_position.norm();
        float theta = std::acos(m_position.y / r);
        float phi = std::atan(m_position.x / m_position.z);

        theta += newTheta;
        phi += newPhi;

        m_up = Vector(0.0f, 1.0f, 0.0f);
        Vector newPosition(r*std::sin(theta)*std::sin(phi), r*std::cos(theta),
                r*std::sin(theta)*std::cos(phi));
        setPosition(newPosition);
        m_prevX = mouseX;
        m_prevY = mouseY;
    }
}


What I was expecting is to be able to rotate the camera around the cube in the scene so that I can see all around it. My code almost achieves this, but I don't understand why after rotating a certain amount the camera jumps to the exact opposite side of the cube.

You can check what weird swap I am talking about this link

What am I missing so that the rotation around the object goes all the way around it?
It is likely that your specific problem arises from a singularity in atan when m_position.z goes to 0. Rather than try to debug that, I'll point out that you don't need to transform your camera position into an angle to then modify it: rather, just create a rotation from your newPhi and newTheta angles, in the form of a rotation matrix or quaternion, and then apply it to your vector, directly rotating it without doing the perilous round-trip to an angle.