Search code examples
c++visual-studioopenglglrotate

OpenGl draw a cylinder with 2 points glRotated


I want to show draw a cylinder that starts at point a and that points to I think the key is in the first glRotated, but this is my first time working with openGL a and b are btVector3

glPushMatrix();
glTranslatef(a.x(), a.y(), a.z());
glRotated(0, b.x(), b.y(), b.z());
glutSolidCylinder(.01, .10 ,20,20);
glPopMatrix();

Any suggestions ??


Solution

  • According to glutsolidcylinder(3) - Linux man page:

    glutSolidCylinder() draws a shaded cylinder, the center of whose base is at the origin and whose axis is along the positive z axis.

    Hence, you have to prepare the transformations respectively:

    • move the center of cylinder to origin (that's (a + b) / 2)
    • rotate that axis of cylinder (that's b - a) becomes z-axis.

    The usage of glRotatef() seems to be mis-understood, also:

    • 1st value is angle of rotation, in degrees
    • 2nd, 3rd, and 4th value are x, y, z of rotation axis.

    This would result in:

    // center of cylinder
    const btVector3 c = 0.5 * (a + b);
    // axis of cylinder
    const btVector3 axis = b - a;
    // determine angle between axis of cylinder and z-axis
    const btVector3 zAxis(0.0, 0.0, 1.0);
    const btScalar angle = zAxis.angle(axis);
    // determine rotation axis to turn axis of cylinder to z-axis
    const btVector3 axisT = zAxis.cross(axis).normalize();
    // do transformations
    glTranslatef(c.x(), c.y(), c.z());
    if (axisT.norm() > 1E-6) { // skip this if axis and z-axis are parallel
      const GLfloat radToDeg = 180.0f / 3.141593f; 
      glRotatef(angle * radToDeg, axisT.x(), axisT.y(), axisT.z());
    }
    glutSolidCylinder(0.1, axis.length(), 20, 20);
    

    I wrote this code out of mind (using the doc. of btVector3 which I've never used before). Thus, please, take this with a grain of salt. (Debugging might be necessary.)

    So, please, keep the following in mind:

    1. The doc. does not mention whether btVector3::angle() returns angle in degree or radians – I assumed radians.

    2. When writing such code, I often accidentally flip things (e.g. rotation into opposite direction). Such things, I usually fix in debugging, and this is probably necessary for the above sample code.

    3. If (b - a) is already along positive or negative z-axis, then (b - a) × (0, 0, 1) will yield a 0-vector. Unfortunately, the doc. of btVector3::normalize() does not mention what happens when applied to a 0-vector. If an exception is thrown in this case, extra checks have to be added, of course.