Ioana
Ioana

Reputation: 33

OPENGL SLOWER ANIMATION on 2 Icosaedres

I have the code below. There are 2 illuminated icosaedres that rotate very very fast. What should I do to make the rotation slower? I'm not very good at OpenGL and I have tried modifying the values from the Idle function but it still doesn't slow down.

void 
display(void)
{
  static GLfloat amb[] =
  {0.4, 0.4, 0.4, 0.0};
  static GLfloat dif[] =
  {1.0, 1.0, 1.0, 0.0};


  amb[3] = dif[3] = cos(s) / 2.0 + 0.5;
  glMaterialfv(GL_FRONT, GL_AMBIENT, amb);
  glMaterialfv(GL_FRONT, GL_DIFFUSE, dif);

  glPushMatrix();
  glTranslatef(-0.3, -0.3, 0.0);
  glRotatef(angle1, 1.0, 5.0, 0.0);
  glCallList(1);        /* render ico display list */
  glPopMatrix();

  glClear(GL_DEPTH_BUFFER_BIT);
  glEnable(GL_LIGHT2);
  glDisable(GL_LIGHT1);
  amb[3] = dif[3] = 0.5 - cos(s * .95) / 2.0;
  glMaterialfv(GL_FRONT, GL_AMBIENT, amb);
  glMaterialfv(GL_FRONT, GL_DIFFUSE, dif);

  glPushMatrix();
  glTranslatef(0.3, 0.3, 0.0);
  glRotatef(angle2, 1.0, 0.0, 5.0);
  glCallList(1);        /* render ico display list */
  glPopMatrix();

}

void 
idle(void)
{
  angle1 = (GLfloat) fmod(angle1 + 0.8, 360.0);
  angle2 = (GLfloat) fmod(angle2 + 1.1, 360.0);
  s += 0.05;
  glutPostRedisplay();
}

void 
visible(int vis)
{
  if (vis == GLUT_VISIBLE)
    glutIdleFunc(idle);
  else
    glutIdleFunc(NULL);
}

Upvotes: 3

Views: 223

Answers (1)

Rabbid76
Rabbid76

Reputation: 210928

In c++ I recommend to use std::chrono, to calculate a time duration:

Remember the start time, before you start the main loop of your application:

#include <chrono>

typedef std::chrono::high_resolution_clock TClock;
typedef std::chrono::duration<long, std::milli> Tms;

TClock::time_point start_time; // global start time

....

start_time = TClock::now();

Calculate the duration time in the idle function:

double time_duration_seconds = 0.0; // past time in seconds

void idle(void)
{
     TClock::time_point current_time = TClock::now();

     long milli_seconds = 
         std::chrono::duration_cast<Tms>( current_time - start_time ).count();

     time_duration_seconds = (double)milli_seconds / 1000.0;
}

The angle for a rotation with a constant interval can be calculated easily. The following code calculates the angle for a full rotation in 5 seconds in degrees:

double interval1 = 5.0; // 5 seconds for 360 degrees
double angle1    = 360.0 * fmod(time_duration_seconds / interval1, 1.0f);

Upvotes: 1

Related Questions