예제 #1
0
int init(int argc, char **argv)	//initialization function
{
	printf("Beginning initialization\n");

	vectorUp.x=0;			//assign the up vector to (0,1,0)
	vectorUp.y=1;
	vectorUp.z=0;

	cameraDefault.location.x=0;	//set up a default camera
	cameraDefault.location.y=0;
	cameraDefault.location.z=5;
	cameraDefault.target.x=0;
	cameraDefault.target.y=0;
	cameraDefault.target.z=-1;

	cameraCurrent = &cameraDefault;	//set the default camera as the current camera

	windowTitle = (char*) &defaultTitle;	//set the window title to be the default
	windowMain.x = 50;				//set up initial window shape
	windowMain.y = 50;
	windowMain.width = 640;
	windowMain.height = 480;

	ratio = 1.0 * windowMain.width / windowMain.height;

	xRot = 0;
	yRot = 0;
	zRot = 0;

	stateFullScreen = 0;	//default is to start in window mode
							//to start in fullscreen mode do NOT
							//change this value, instead call
							//toggleFullScreen() after the window
							//has been created

	frame = 0;				//set up counters
	timebase = 0;

	//GLUT initialization follows, don't worry about it
	glutInit(&argc, argv);
	glutInitWindowPosition(windowMain.x, windowMain.y);
	glutInitWindowSize(windowMain.width, windowMain.height);
	glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
	printf("Creating window \"%s\"\n", windowTitle);
	glutCreateWindow(windowTitle);
	glutDisplayFunc(draw);
	glutIdleFunc(draw);
	glutReshapeFunc(resize);
	glutKeyboardFunc(normalKey);
	glutSpecialFunc(specialKey);
	glutMouseFunc(mouse);
	glutMotionFunc(mouseActive);
	glutPassiveMotionFunc(mousePassive);
	glutEntryFunc(mouseEntry);

	//initialize timers
	time = glutGet(GLUT_ELAPSED_TIME);
	timepassed = 0;

	//initialize quadratics
	quadratic = gluNewQuadric();
	gluQuadricNormals(quadratic, GLU_SMOOTH);

	printf("Initialization complete\n");

	return 1;
}
예제 #2
0
파일: proj3.cpp 프로젝트: guwu/cs553
void
Display()
{
	if (DebugOn != 0)
	{
		fprintf(stderr, "Display\n");
	}


	// set which window we want to do the graphics into:

	glutSetWindow(MainWindow);


	// erase the background:

	glDrawBuffer(GL_BACK);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glEnable(GL_DEPTH_TEST);


	// specify shading to be flat:

	glShadeModel(GL_FLAT);


	// set the viewport to a square centered in the window:

	GLsizei vx = glutGet(GLUT_WINDOW_WIDTH);
	GLsizei vy = glutGet(GLUT_WINDOW_HEIGHT);
	GLsizei v = vx < vy ? vx : vy;			// minimum dimension
	GLint xl = (vx - v) / 2;
	GLint yb = (vy - v) / 2;
	glViewport(xl, yb, v, v);


	// set the viewing volume:
	// remember that the Z clipping  values are actually
	// given as DISTANCES IN FRONT OF THE EYE
	// USE gluOrtho2D( ) IF YOU ARE DOING 2D !

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	if (WhichProjection == ORTHO)
		glOrtho(-3., 3., -3., 3., 0.1, 1000.);
	else
		gluPerspective(90., 1., 0.1, 1000.);


	// place the objects into the scene:

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();


	// set the eye position, look-at position, and up-vector:
	// IF DOING 2D, REMOVE THIS -- OTHERWISE ALL YOUR 2D WILL DISAPPEAR !

	gluLookAt(0., 0., 3., 0., 0., 0., 0., 1., 0.);


	// translate the objects in the scene:
	// note the minus sign on the z value
	// this is to make the appearance of the glui z translate
	// widget more intuitively match the translate behavior
	// DO NOT TRANSLATE IN Z IF YOU ARE DOING 2D !

	glTranslatef((GLfloat)TransXYZ[0], (GLfloat)TransXYZ[1], -(GLfloat)TransXYZ[2]);


	// rotate the scene:
	// DO NOT ROTATE (EXCEPT ABOUT Z) IF YOU ARE DOING 2D !

	glRotatef((GLfloat)Yrot, 0., 1., 0.);
	glRotatef((GLfloat)Xrot, 1., 0., 0.);
	glMultMatrixf((const GLfloat *)RotMatrix);


	// uniformly scale the scene:

	glScalef((GLfloat)Scale, (GLfloat)Scale, (GLfloat)Scale);
	GLfloat scale2 = 1. + Scale2;		// because glui translation starts at 0.
	if (scale2 < MINSCALE)
		scale2 = MINSCALE;
	glScalef((GLfloat)scale2, (GLfloat)scale2, (GLfloat)scale2);


	// set the fog parameters:
	// DON'T NEED THIS IF DOING 2D !

	if (DepthCueOn != 0)
	{
		glFogi(GL_FOG_MODE, FOGMODE);
		glFogfv(GL_FOG_COLOR, FOGCOLOR);
		glFogf(GL_FOG_DENSITY, FOGDENSITY);
		glFogf(GL_FOG_START, FOGSTART);
		glFogf(GL_FOG_END, FOGEND);
		glEnable(GL_FOG);
	}
	else
	{
		glDisable(GL_FOG);
	}


	// possibly draw the axes:

	if (AxesOn != 0)
	{
		glColor3fv(&Colors[WhichColor][0]);
		glCallList(AxesList);
	}


	// set the color of the object:

	glColor3fv(Colors[WhichColor]);


	// draw the current object:

	//glCallList( PointList );
	glPointSize(PointSize);
	glBegin(GL_POINTS);
	for (int i = 0; i < NX; i++)
	{
		//check X slider
		if (Nodes[i][0][0].x < XLowHigh[0] || Nodes[i][0][0].x > XLowHigh[1])
			continue;
		for (int j = 0; j < NY; j++)
		{
			//check Y slider
			if (Nodes[0][j][0].y < YLowHigh[0] || Nodes[0][j][0].y > YLowHigh[1])
				continue;

			for (int k = 0; k < NZ; k++)
			{
				//check Z slider
				if (Nodes[0][0][k].z < ZLowHigh[0] || Nodes[0][0][k].z > ZLowHigh[1])
					continue;
				//check temperature slider
				if (Nodes[i][j][k].t > TempLowHigh[0] && Nodes[i][j][k].t < TempLowHigh[1])
				{

					// check the radius too:


					if (Nodes[i][j][k].rad > RadLowHigh[0] && Nodes[i][j][k].rad < RadLowHigh[1])
					{
						// check the gradient too:
						if (Nodes[i][j][k].grad > GradLowHigh[0] && Nodes[i][j][k].grad < GradLowHigh[1])
						{
							// finally draw the point if it passes all the tests:
							glColor3f(Nodes[i][j][k].rgb[0], Nodes[i][j][k].rgb[1], Nodes[i][j][k].rgb[2]);
							glVertex3f(Nodes[i][j][k].x, Nodes[i][j][k].y, Nodes[i][j][k].z);

						}

					}
				}
			}
		}
	}

	glEnd();


	// draw some gratuitous text that just rotates on top of the scene:

	glDisable( GL_DEPTH_TEST );
	glColor3f( 0., 1., 1. );
	//DoRasterString( 0., 1., 0., "Text That Moves" );


	// draw some gratuitous text that is fixed on the screen:
	//
	// the projection matrix is reset to define a scene whose
	// world coordinate system goes from 0-100 in each axis
	//
	// this is called "percent units", and is just a convenience
	//
	// the modelview matrix is reset to identity as we don't
	// want to transform these coordinates

	glDisable( GL_DEPTH_TEST );
	glMatrixMode( GL_PROJECTION );
	glLoadIdentity( );
	gluOrtho2D( 0., 100.,     0., 100. );
	glMatrixMode( GL_MODELVIEW );
	glLoadIdentity( );
	glColor3f( 1., 1., 1. );
	//DoRasterString( 5., 5., 0., "Text That Doesn't" );


	// swap the double-buffered framebuffers:

	glutSwapBuffers( );


	// be sure the graphics buffer has been sent:
	// note: be sure to use glFlush( ) here, not glFinish( ) !

	glFlush( );
}
예제 #3
0
파일: timer.cpp 프로젝트: CPutz/Mandelbrot
void Timer::start() {
	this->tStart = glutGet( GLUT_ELAPSED_TIME );
    this->isRunning = true;
    this->wasStarted = true;
}
예제 #4
0
void display(void)
{
	kuhl_limitfps(100);
	dgr_update();
	// Make sure slaves get updates ASAP
	dgr_setget("currentTex", &currentTexture, sizeof(int));


	/* If the texture has changed since we were previously in display() */
	if(alreadyDisplayedTexture != currentTexture)
	{
		// Load the new texture
		loadTexture(currentTexture);
		// Keep a record of which texture we are currently displaying
		// so we can detect when DGR changes currentTexture on a
		// slave.
		alreadyDisplayedTexture = currentTexture;
	}

	/* The view frustum is an orthographic frustum for this
	 * application. The size of the frustum doesn't matter much, but
	 * the aspect ratio of the frustum should match the aspect ratio
	 * of the screen/window. */
	float frustum[6], masterFrustum[6];
	
	/* The following two methods will get the master view frustum and
	 * the current process view frustum. If we are running in a
	 * standalone version, these two frustums will be the same. */
	projmat_get_master_frustum(masterFrustum);
	projmat_get_frustum(frustum, -1, -1); // frustum of this process (master or slave)

	/* Set this view frustum for this process. */
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(frustum[0],frustum[1],
	        frustum[2],frustum[3],
	        -1, 1);
	glMatrixMode(GL_MODELVIEW);

	// Middle of master frustum in the vertical direction. It divides the top
	// tiles from the bottom tiles.
	float masterFrustumMid = (masterFrustum[2]+masterFrustum[3])/2;
	// Dimensions of the master view frustum
	float masterFrustumWidth  = masterFrustum[1]-masterFrustum[0];
	float masterFrustumHeight = masterFrustum[3]-masterFrustum[2];

	// The width of the quad (in frustum units). Since the image will
	// be stretched to fit the screen vertically, and our units are in
	// frustum units, the width of the tile is the height of the
	// frustum times the aspect ratio divided by the number of tiles
	// in the horizontal direction.
	float quadWidth = aspectRatio * masterFrustumHeight;
	float tileWidth = quadWidth/numTiles;

// TODO: Maybe just scale the image vertically if the image almost fits in the screen horizontally?

	int msSincePictureDisplayed = glutGet(GLUT_ELAPSED_TIME)-lastAdvance;
	int scrollStatus = 0; // 0=don't need to scroll or done scrolling, 1=currently scrolling
	if(masterFrustumWidth < quadWidth)// do we need to scroll on this image
	{
		// Do we still need to scroll?
		if(scrollAmount < quadWidth-masterFrustumWidth)
			scrollStatus = 1;

		if(scrollStatus == 1)
		{
			// Wait a few seconds before scrolling. It takes a while
			// for all slaves on IVS to get the images.
			if(msSincePictureDisplayed > 5000)
				scrollAmount = ((msSincePictureDisplayed-5000) / (SCROLL_SPEED*1000.0))*masterFrustumWidth;
			else
				scrollAmount = 0;

			// If we calculated the scroll amount to be the largest
			// scrollAmount we'll need
			if(scrollAmount > quadWidth-masterFrustumWidth)
			{
				// dwell at the end of the image even if autoadvance is on.
				int now = glutGet(GLUT_ELAPSED_TIME);
				// make sure we still have a few seconds before advancing
				if(SLIDESHOW_WAIT*1000-(now-lastAdvance) < 3000)
				{
					// Go back and set lastAdvance time so we have
					// some time to dwell here.
					lastAdvance = now-SLIDESHOW_WAIT*1000+3000;
				}
			}
		}
	}

	dgr_setget("scrollAmount", &scrollAmount, sizeof(float));

	/* If autoadvance is set and we are not scrolling (or done
	 * scrolling) figure out if it is now time to advance to the next
	 * image. */
	if(autoAdvance == 1 && scrollStatus != 1)
	{
//		printf("time since last advance %d\n", glutGet(GLUT_ELAPSED_TIME)-lastAdvance);
		if(glutGet(GLUT_ELAPSED_TIME)-lastAdvance > SLIDESHOW_WAIT*1000) // time to show new image:
		{
			currentTexture = getNextTexture();
			loadTexture(currentTexture);
			return;
		}
	}

	glClear(GL_COLOR_BUFFER_BIT);
	glEnable(GL_TEXTURE_2D);
	glColor3f(1,1,1); // color of quad

	// Draw the top and bottom quad for each of the tiles going across the screen horizontally. */
	for(GLuint i=0; i<numTiles*2; i=i+2)
	{
		float tileLeft  = (i/2  )*tileWidth + masterFrustum[0];
		float tileRight = (i/2+1)*tileWidth + masterFrustum[0];
		
		// Draw bottom tile
		glBindTexture(GL_TEXTURE_2D, texNames[i]);
		glBegin(GL_QUADS);
		glTexCoord2f(0.0, 0.0); glVertex2d(tileLeft -scrollAmount, masterFrustum[2]); // lower left
		glTexCoord2f(1.0, 0.0); glVertex2d(tileRight-scrollAmount, masterFrustum[2]); // lower right
		glTexCoord2f(1.0, 1.0); glVertex2d(tileRight-scrollAmount, masterFrustumMid); // upper right
		glTexCoord2f(0.0, 1.0); glVertex2d(tileLeft -scrollAmount, masterFrustumMid); // upper left
		glEnd();

		// Draw top tile
		glBindTexture(GL_TEXTURE_2D, texNames[i+1]);
		glBegin(GL_QUADS);
		glTexCoord2f(0.0, 0.0); glVertex2d(tileLeft -scrollAmount, masterFrustumMid); // lower left
		glTexCoord2f(1.0, 0.0); glVertex2d(tileRight-scrollAmount, masterFrustumMid); // lower right
		glTexCoord2f(1.0, 1.0); glVertex2d(tileRight-scrollAmount, masterFrustum[3]); // upper right
		glTexCoord2f(0.0, 1.0); glVertex2d(tileLeft -scrollAmount, masterFrustum[3]); // upper left
		glEnd();
	}

	glDisable(GL_TEXTURE_2D);

	/* Draw filename label on top of a quad. */
	glColor4f(0,0,0,.3);
	glBegin(GL_QUADS);
	glVertex2d(-1,-1);
	glVertex2d(-.5,-1);
	glVertex2d(-.5,-.96);
	glVertex2d(-1,-.96);
	glEnd();

	glColor4f(1,1,1,.9);
	glRasterPos2f(-.98,-.98);
	void *font = GLUT_BITMAP_TIMES_ROMAN_24;
	char *str = globalargv[currentTexture];
	for(GLuint i=0; i<strlen(str); i++)
		glutBitmapCharacter(font, str[i]);

	/* Flush and swap the OpenGL buffers. */
	glFlush();
	glutSwapBuffers();
	glutPostRedisplay();
}
예제 #5
0
void Idle() {
  current_time = glutGet(GLUT_ELAPSED_TIME);

  int dt = current_time - last_time;

  if (g_eCurrentScene >= 3) {
    if (mouse_state == GLUT_DOWN) {
      horizontalAngle +=
          mouseSpeed * float(800 / 2 - mouse_x);  // 800 = window width
      verticalAngle +=
          mouseSpeed * float(600 / 2 - mouse_y);  // 600 = window height

      // Direction : Spherical coordinates to Cartesian coordinates conversion
      direction = glm::vec3(cos(verticalAngle) * sin(horizontalAngle),
                            sin(verticalAngle),
                            cos(verticalAngle) * cos(horizontalAngle));

      // Right vector
      right = glm::vec3(sin(horizontalAngle - PI / 2.0f), 0,
                        cos(horizontalAngle - PI / 2.0f));

      // Up vector
      up = glm::cross(right, direction);
    }

    // Move forward
    if (sp_key == GLUT_KEY_UP) {
      position += direction * (dt * cursor_speed);
    }
    // Move backward
    if (sp_key == GLUT_KEY_DOWN) {
      position -= direction * (dt * cursor_speed);
    }
    // Strafe right
    if (sp_key == GLUT_KEY_RIGHT) {
      position += right * (dt * cursor_speed);
    }
    // Strafe left
    if (sp_key == GLUT_KEY_LEFT) {
      position -= right * (dt * cursor_speed);
    }
    sp_key = 0;

    // Camera matrix
    View = glm::lookAt(position, position + direction, up);
    glutPostRedisplay();

    std::cout << position.x << " " << position.y << " " << position.z
              << std::endl;
  }
  if (g_eCurrentScene == 5) {
    counter = counter + 0.002 * dt;
    MODEL_EVERYTHING = glm::translate(MODEL_EVERYTHING, glm::vec3(0, 0, 0.0013 * counter));
    MODEL_LEG_1 = glm::rotate(MODEL_LEG_1, float(cos(counter)), glm::vec3(1, 0, 0));
    MODEL_LEG_2 = glm::rotate(MODEL_LEG_2, float(-cos(counter)), glm::vec3(1, 0, 0));
  }
  if (g_eCurrentScene == 6) {
    counter = counter + 0.002 * dt;
    MODEL_EVERYTHING = glm::translate(MODEL_EVERYTHING, glm::vec3(0, 0, 0.0013 * counter));
    MODEL_LEG_1 = glm::rotate(MODEL_LEG_1, float(cos(counter)), glm::vec3(1, 0, 0));
    MODEL_LEG_2 = glm::rotate(MODEL_LEG_2, float(-cos(counter)), glm::vec3(1, 0, 0));
    
    // Follow legs 
    position += glm::vec3(0, 0, 0.0013 * counter);
    View = glm::lookAt(position, position + direction, up);
    glutPostRedisplay();
  }
  last_time = current_time;  // update when the last timer;
}
예제 #6
0
//------------------------------------------------------------
ofPoint ofAppGlutWindow::getWindowPosition(){
	int x = glutGet(GLUT_WINDOW_X);
	int y = glutGet(GLUT_WINDOW_Y);
	return ofPoint(x,y,0);
}
예제 #7
0
//------------------------------------------------------------
void ofAppGlutWindow::display(void){

	//--------------------------------
	// when I had "glutFullScreen()"
	// in the initOpenGl, I was gettings a "heap" allocation error
	// when debugging via visual studio.  putting it here, changes that.
	// maybe it's voodoo, or I am getting rid of the problem
	// by removing something unrelated, but everything seems
	// to work if I put fullscreen on the first frame of display.

	if (windowMode != OF_GAME_MODE){
		if ( bNewScreenMode ){
			if( windowMode == OF_FULLSCREEN){

				//----------------------------------------------------
				// before we go fullscreen, take a snapshot of where we are:
				nonFullScreenX = glutGet(GLUT_WINDOW_X);
				nonFullScreenY = glutGet(GLUT_WINDOW_Y);
				//----------------------------------------------------

				glutFullScreen();
#if 0
				#ifdef TARGET_OSX
					SetSystemUIMode(kUIModeAllHidden,NULL);
					#ifdef MAC_OS_X_VERSION_10_7 //needed for Lion as when the machine reboots the app is not at front level
						if( nFrameCount <= 10 ){  //is this long enough? too long? 
							ProcessSerialNumber psn;							
							OSErr err = GetCurrentProcess( &psn );
							if ( err == noErr ){
								SetFrontProcess( &psn );
							}
						}
					#endif
				#endif
#endif
			}else if( windowMode == OF_WINDOW ){

				glutReshapeWindow(requestedWidth, requestedHeight);

				//----------------------------------------------------
				// if we have recorded the screen posion, put it there
				// if not, better to let the system do it (and put it where it wants)
				if (nFrameCount > 0){
					glutPositionWindow(nonFullScreenX,nonFullScreenY);
				}
				//----------------------------------------------------
#if 0
				#ifdef TARGET_OSX
					SetSystemUIMode(kUIModeNormal,NULL);
				#endif
#endif
			}
			bNewScreenMode = false;
		}
	}

	// set viewport, clear the screen
	ofViewport(0, 0, glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT));		// used to be glViewport( 0, 0, width, height );
	float * bgPtr = ofBgColorPtr();
	bool bClearAuto = ofbClearBg();

    // to do non auto clear on PC for now - we do something like "single" buffering --
    // it's not that pretty but it work for the most part

    #ifdef TARGET_WIN32
    if (bClearAuto == false){
        glDrawBuffer (GL_FRONT);
    }
    #endif

	if ( bClearAuto == true || nFrameCount < 3){
		ofClear(bgPtr[0]*255,bgPtr[1]*255,bgPtr[2]*255, bgPtr[3]*255);
	}

	if( bEnableSetupScreen )ofSetupScreen();

	ofNotifyDraw();

    #ifdef TARGET_WIN32
    if (bClearAuto == false){
        // on a PC resizing a window with this method of accumulation (essentially single buffering)
        // is BAD, so we clear on resize events.
        if (nFramesSinceWindowResized < 3){
        	ofClear(bgPtr[0]*255,bgPtr[1]*255,bgPtr[2]*255, bgPtr[3]*255);
        } else {
            if ( (nFrameCount < 3 || nFramesSinceWindowResized < 3) && bDoubleBuffered)    glutSwapBuffers();
            else                                                     glFlush();
        }
    } else {
        if(bDoubleBuffered){
			glutSwapBuffers();
		} else{
			glFlush();
		}
    }
    #else
		if (bClearAuto == false){
			// in accum mode resizing a window is BAD, so we clear on resize events.
			if (nFramesSinceWindowResized < 3){
				ofClear(bgPtr[0]*255,bgPtr[1]*255,bgPtr[2]*255, bgPtr[3]*255);
			}
		}
		if(bDoubleBuffered){
			glutSwapBuffers();
		} else{
			glFlush();
		}
    #endif

    nFramesSinceWindowResized++;

	//fps calculation moved to idle_cb as we were having fps speedups when heavy drawing was occuring
	//wasn't reflecting on the actual app fps which was in reality slower.
	//could be caused by some sort of deferred drawing?

	nFrameCount++;		// increase the overall frame count

	//setFrameNum(nFrameCount); // get this info to ofUtils for people to access

}
예제 #8
0
void
redraw(void)
{
  int begin, end, elapsed;
  int i, j;
  float amplitude;

  if (set_timeout) {
    begin = glutGet(GLUT_ELAPSED_TIME);
  }
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glPushMatrix();

  if (mode != DRUM) {
    glScalef(size, size, size);
  }
  switch (mode) {
  case SQUARES:

#define COLS 6
#define TILE_TEX_W (1.0/COLS)
#define ROWS 6
#define TILE_TEX_H (1.0/ROWS)

    glTranslatef(-COLS / 2.0 + .5, -ROWS / 2.0 + .5, 0);
    for (i = 0; i < COLS; i++) {
      for (j = 0; j < ROWS; j++) {

        glPushMatrix();
        glTranslatef(i, j, 0);
        glRotatef(angle, 0, 1, 1);
        glBegin(GL_QUADS);
        glTexCoord2f(i * TILE_TEX_W, j * TILE_TEX_H);
        glVertex2f(-.5, -.5);
        glTexCoord2f((i + 1) * TILE_TEX_W, j * TILE_TEX_H);
        glVertex2f(.5, -.5);
        glTexCoord2f((i + 1) * TILE_TEX_W, (j + 1) * TILE_TEX_H);
        glVertex2f(.5, .5);
        glTexCoord2f(i * TILE_TEX_W, (j + 1) * TILE_TEX_H);
        glVertex2f(-.5, .5);
        glEnd();
        glPopMatrix();

      }
    }
    break;
  case DRUM:

#undef COLS
#undef TILE_TEX_W
#undef ROWS
#undef TILE_TEX_H
#define COLS 12
#define TILE_TEX_W (1.0/COLS)
#define ROWS 12
#define TILE_TEX_H (1.0/ROWS)

    glRotatef(angle, 0, 0, 1);
    glTranslatef(-COLS / 2.0 + .5, -ROWS / 2.0 + .5, 0);
    amplitude = 0.4 * sin(tick2 / 6.0);
    for (i = 0; i < COLS; i++) {
      for (j = 0; j < ROWS; j++) {

#define Z(x,y)  (((COLS-(x))*(x) + (ROWS-(y))*(y)) * amplitude) - 28.0

        glPushMatrix();
        glTranslatef(i, j, 0);
        glBegin(GL_QUADS);
        glTexCoord2f(i * TILE_TEX_W, j * TILE_TEX_H);
        glVertex3f(-.5, -.5, Z(i, j));
        glTexCoord2f((i + 1) * TILE_TEX_W, j * TILE_TEX_H);
        glVertex3f(.5, -.5, Z(i + 1, j));
        glTexCoord2f((i + 1) * TILE_TEX_W, (j + 1) * TILE_TEX_H);
        glVertex3f(.5, .5, Z(i + 1, j + 1));
        glTexCoord2f(i * TILE_TEX_W, (j + 1) * TILE_TEX_H);
        glVertex3f(-.5, .5, Z(i, j + 1));
        glEnd();
        glPopMatrix();

      }
    }
    break;
  case CUBE:
    glRotatef(angle, 0, 1, 0);
    glBegin(GL_QUADS);

    /* front */
    glTexCoord2f(0.0, 0.0);
    glVertex3f(-1.0, -1.0, 1.0);
    glTexCoord2f(1.0, 0.0);
    glVertex3f(1.0, -1.0, 1.0);
    glTexCoord2f(1.0, 1.0);
    glVertex3f(1.0, 1.0, 1.0);
    glTexCoord2f(0.0, 1.0);
    glVertex3f(-1.0, 1.0, 1.0);

    /* back */
    glTexCoord2f(0.0, 1.0);
    glVertex3f(-1.0, 1.0, -1.0);
    glTexCoord2f(1.0, 1.0);
    glVertex3f(1.0, 1.0, -1.0);
    glTexCoord2f(1.0, 0.0);
    glVertex3f(1.0, -1.0, -1.0);
    glTexCoord2f(0.0, 0.0);
    glVertex3f(-1.0, -1.0, -1.0);

    /* left */
    glTexCoord2f(0.0, 0.0);
    glVertex3f(-1.0, -1.0, -1.0);
    glTexCoord2f(1.0, 0.0);
    glVertex3f(-1.0, -1.0, 1.0);
    glTexCoord2f(1.0, 1.0);
    glVertex3f(-1.0, 1.0, 1.0);
    glTexCoord2f(0.0, 1.0);
    glVertex3f(-1.0, 1.0, -1.0);

    /* right */
    glTexCoord2f(0.0, 1.0);
    glVertex3f(1.0, 1.0, -1.0);
    glTexCoord2f(1.0, 1.0);
    glVertex3f(1.0, 1.0, 1.0);
    glTexCoord2f(1.0, 0.0);
    glVertex3f(1.0, -1.0, 1.0);
    glTexCoord2f(0.0, 0.0);
    glVertex3f(1.0, -1.0, -1.0);

    glEnd();
  }

  glPopMatrix();
  glutSwapBuffers();
  if (set_timeout) {
    set_timeout = 0;
    end = glutGet(GLUT_ELAPSED_TIME);
    elapsed = end - begin;
    if (elapsed > interval) {
      glutTimerFunc(0, animate, 1);
    } else {
      glutTimerFunc(interval - elapsed, animate, 1);
    }
  }
}
예제 #9
0
static void mainLoop(void)
{
	static int ms_prev;
	int ms;
	float s_elapsed;
	ARUint8 *image;
    AR2VideoBufferT *movieBuffer;
	ARdouble err;

    int             j, k;
	
	// Find out how long since mainLoop() last ran.
	ms = glutGet(GLUT_ELAPSED_TIME);
	s_elapsed = (float)(ms - ms_prev) * 0.001f;
	if (s_elapsed < 0.01f) return; // Don't update more often than 100 Hz.
	ms_prev = ms;
	
	// Grab a movie frame (if available).
    if ((movieBuffer = ar2VideoGetImage(gMovieVideo)) != NULL) {
        if (movieBuffer->buff && movieBuffer->fillFlag)
            gMovieImage = movieBuffer->buff;
    }
    
	// Grab a video frame.
	if ((image = arVideoGetImage()) != NULL) {
		gARTImage = image;	// Save the fetched image.
        
		gCallCountMarkerDetect++; // Increment ARToolKit FPS counter.
		
		// Detect the markers in the video frame.
		if (arDetectMarker(gARHandle, gARTImage) < 0) {
			exit(-1);
		}
		
		// Check through the marker_info array for highest confidence
		// visible marker matching our preferred pattern.
		k = -1;
		for (j = 0; j < gARHandle->marker_num; j++) {
			if (gARHandle->markerInfo[j].id == gPatt_id) {
				if (k == -1) k = j; // First marker detected.
				else if (gARHandle->markerInfo[j].cf > gARHandle->markerInfo[k].cf) k = j; // Higher confidence marker detected.
			}
		}
		
		if (k != -1) {
			// Get the transformation between the marker and the real camera into gPatt_trans.
            if (gPatt_found && useContPoseEstimation) {
                err = arGetTransMatSquareCont(gAR3DHandle, &(gARHandle->markerInfo[k]), gPatt_trans, gPatt_width, gPatt_trans);
            } else {
                err = arGetTransMatSquare(gAR3DHandle, &(gARHandle->markerInfo[k]), gPatt_width, gPatt_trans);
                // Marker has appeared, so un-pause movie.
                ar2VideoCapStart(gMovieVideo);
            }
			gPatt_found = TRUE;
		} else {
            if (gPatt_found) {
                // Marker has disappeared, so pause movie.
                ar2VideoCapStop(gMovieVideo);
            }
			gPatt_found = FALSE;
		}
		
		// Tell GLUT the display has changed.
		glutPostRedisplay();
	}
}
예제 #10
0
//-------------------------------------------------------------------------
void CPUSectionTimer::EndSection()
{
    current = glutGet(GLUT_ELAPSED_TIME) - startTime;
}
예제 #11
0
// Callback handler for special-key event
void specialKeys(int key, int x, int y) {
	switch (key) {
		case GLUT_KEY_F1:														// F1: Toggle between full-screen and windowed mode
			fullScreenMode = !fullScreenMode;									// Toggle state
			if (fullScreenMode) {												// Full-screen mode
				windowPosX   = glutGet(GLUT_WINDOW_X);							// Save parameters
				windowPosY   = glutGet(GLUT_WINDOW_Y);
				windowWidth  = glutGet(GLUT_WINDOW_WIDTH);
				windowHeight = glutGet(GLUT_WINDOW_HEIGHT);
				glutFullScreen();												// Switch into full screen
			} else {															// Windowed mode
				glutReshapeWindow(windowWidth, windowHeight);					// Switch into windowed mode
				glutPositionWindow(windowPosX,windowPosY);						// Postion top-left corner
		}
        break;
		case GLUT_KEY_UP:														// Up: increase speed
			if(eyePositionVerticalDeg < 88.0 ){
				eyePositionVerticalDeg +=2.0;
				tmpY = 20*sin(eyePositionVerticalDeg* 2*PI / 360.0) * eyePositionZoom;
				tmpX = 20*sin(eyePositionHorizontalDeg* 2*PI / 360.0)*cos(eyePositionVerticalDeg* 2*PI / 360.0) * eyePositionZoom;
				tmpZ = 20*cos(eyePositionHorizontalDeg* 2*PI / 360.0)*cos(eyePositionVerticalDeg* 2*PI / 360.0) * eyePositionZoom;
				if(tmpX <= 20.0 && tmpZ <= 40.0 && tmpX >=-20.0 && tmpZ >= -40 && tmpY >= -2.0 && tmpY < 20.0){
					eyePositionY = tmpY;
					eyePositionX = tmpX;
					eyePositionZ = tmpZ;
				}
				else eyePositionVerticalDeg -=2.0;
			}
			break;
		case GLUT_KEY_DOWN:														// Up: decrease speed
			if(eyePositionVerticalDeg > -88.0){
				eyePositionVerticalDeg -=2.0;
				tmpY = 20*sin(eyePositionVerticalDeg* 2*PI / 360.0) * eyePositionZoom;
				tmpX = 20*sin(eyePositionHorizontalDeg* 2*PI / 360.0)*cos(eyePositionVerticalDeg* 2*PI / 360.0) * eyePositionZoom;
				tmpZ = 20*cos(eyePositionHorizontalDeg* 2*PI / 360.0)*cos(eyePositionVerticalDeg* 2*PI / 360.0) * eyePositionZoom;
				if(tmpX <= 20.0 && tmpZ <= 40.0 && tmpX >=-20.0 && tmpZ >= -40 && tmpY >= -2.0 && tmpY < 20.0){
					eyePositionY = tmpY;
					eyePositionX = tmpX;
					eyePositionZ = tmpZ;
				}
				else eyePositionVerticalDeg +=2.0;
			}
			break;
		case GLUT_KEY_LEFT:														// Up: increase speed
			if(eyePositionHorizontalDeg > 0.0){
				eyePositionHorizontalDeg -=4.0;
				tmpX = 20*sin(eyePositionHorizontalDeg* 2*PI / 360.0)*cos(eyePositionVerticalDeg* 2*PI / 360.0) * eyePositionZoom;
				tmpZ = 20*cos(eyePositionHorizontalDeg* 2*PI / 360.0)*cos(eyePositionVerticalDeg* 2*PI / 360.0) * eyePositionZoom;
				if(tmpX <= 20.0 && tmpZ <= 40.0 && tmpX >=-20.0 && tmpZ >= -40){
					eyePositionX = tmpX;
					eyePositionZ = tmpZ;
				}
				else eyePositionHorizontalDeg +=4.0;
			}
			else eyePositionHorizontalDeg = 360.0;
			break;
		case GLUT_KEY_RIGHT:														// Up: decrease speed
			if(eyePositionHorizontalDeg < 360.0){
				eyePositionHorizontalDeg +=4.0;
				tmpX = 20*sin(eyePositionHorizontalDeg* 2*PI / 360.0)*cos(eyePositionVerticalDeg* 2*PI / 360.0) * eyePositionZoom;
				tmpZ = 20*cos(eyePositionHorizontalDeg* 2*PI / 360.0)*cos(eyePositionVerticalDeg* 2*PI / 360.0) * eyePositionZoom;
				if(tmpX <= 20.0 && tmpZ <= 40.0 && tmpX >=-20.0 && tmpZ >= -40){
				eyePositionX = tmpX;
				eyePositionZ = tmpZ;
				}
				else eyePositionHorizontalDeg -=4.0;
			}
			else eyePositionHorizontalDeg = 0.0;
			break;
		case GLUT_KEY_PAGE_UP:														// Up: decrease speed
			if(eyePositionZoom > 0.1){
				eyeZoomTmp = eyePositionZoom * 0.99;
				tmpX = 20*sin(eyePositionHorizontalDeg* 2*PI / 360.0)*cos(eyePositionVerticalDeg* 2*PI / 360.0) * eyeZoomTmp;
				tmpY = 20*sin(eyePositionVerticalDeg* 2*PI / 360.0) * eyeZoomTmp;
				tmpZ = 20*cos(eyePositionHorizontalDeg* 2*PI / 360.0)*cos(eyePositionVerticalDeg* 2*PI / 360.0) * eyeZoomTmp;
				if(tmpX <= 20.0 && tmpZ <= 40.0 && tmpX >=-20.0 && tmpZ >= -40 && tmpY >= -2.0 && tmpY < 20.0){
					eyePositionX = tmpX;
					eyePositionY = tmpY;
					eyePositionZ = tmpZ;
					eyePositionZoom = eyeZoomTmp;
				}
			}
			break;
		case GLUT_KEY_PAGE_DOWN:														// Up: decrease speed
			if(eyePositionZoom < 10.0 ){
				eyeZoomTmp = eyePositionZoom * 1.01;
				tmpX = 20*sin(eyePositionHorizontalDeg* 2*PI / 360.0)*cos(eyePositionVerticalDeg* 2*PI / 360.0) * eyeZoomTmp;
				tmpY = 20*sin(eyePositionVerticalDeg* 2*PI / 360.0) * eyeZoomTmp;
				tmpZ = 20*cos(eyePositionHorizontalDeg* 2*PI / 360.0)*cos(eyePositionVerticalDeg* 2*PI / 360.0) * eyeZoomTmp;
				if(tmpX <= 20.0 && tmpZ <= 40.0 && tmpX >=-20.0 && tmpZ >= -40 && tmpY >= -2.0 && tmpY < 20.0){
					eyePositionX = tmpX;
					eyePositionY = tmpY;
					eyePositionZ = tmpZ;
					eyePositionZoom = eyeZoomTmp;
				}
			}
			break;
		case GLUT_KEY_END:														// Up: decrease speed
			if(lookAtPositionY > -2.0){
				lookAtPositionY -= 0.5;
				//eyePositionY -= 0.5;
			}
			break;
		case GLUT_KEY_HOME:														// Up: decrease speed
			if(lookAtPositionY < 20.0){
				lookAtPositionY += 0.5;
				//eyePositionY += 0.5;
			}
			break;
			
   }
}
예제 #12
0
//-------------------------------------------------------------------------
void CPUSectionTimer::StartSection()
{
    startTime = glutGet(GLUT_ELAPSED_TIME);
}
예제 #13
0
void PerspectiveCamera::applyView()
{
	gluPerspective(angle,glutGet(GLUT_WINDOW_WIDTH)/glutGet(GLUT_WINDOW_HEIGHT),nearF,farF);
	gluLookAt(position[0],position[1],position[2],target[0],target[1],target[2],0,1,0);
}
예제 #14
0
static void
Idle(void)
{
   Rot = glutGet(GLUT_ELAPSED_TIME) * 0.1;
   glutPostRedisplay();
}
예제 #15
0
static void Display( void )
{
   float x, y;
   float xStep;
   float yStep;
   double t0, t1;
   double triRate;
   double pixelRate;
   int triCount;
   int i;
   float red[3] = { 1.0, 0.0, 0.0 };
   float blue[3] = { 0.0, 0.0, 1.0 };

   xStep = yStep = sqrt( 2.0 * Size );

   glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

   triCount = 0;
   t0 = glutGet(GLUT_ELAPSED_TIME) * 0.001;
   if (Texture) {
      float uStep = xStep / Width;
      float vStep = yStep / Height;
      float u, v;
      for (i=0; i<Loops; i++) {
	 for (y=1.0, v=0.0f; y<Height-yStep; y+=yStep, v+=vStep) {
	    glBegin(GL_TRIANGLE_STRIP);
	    for (x=1.0, u=0.0f; x<Width; x+=xStep, u+=uStep) {
	       glColor3fv(red);
	       glTexCoord2f(u, v);	    
	       glVertex2f(x, y);
	       glColor3fv(blue);
	       glTexCoord2f(u, v+vStep);
	       glVertex2f(x, y+yStep);
	       triCount += 2;
	    }
	    glEnd();
	    triCount -= 2;
	 }
      }
   }
   else {
      for (i=0; i<Loops; i++) {
	 for (y=1.0; y<Height-yStep; y+=yStep) {
	    glBegin(GL_TRIANGLE_STRIP);
	    for (x=1.0; x<Width; x+=xStep) {
	       glColor3fv(red);
	       glVertex2f(x, y);
	       glColor3fv(blue);
	       glVertex2f(x, y+yStep);
	       triCount += 2;
	    }
	    glEnd();
	    triCount -= 2;
	 }
      }
   }
   glFinish();
   t1 = glutGet(GLUT_ELAPSED_TIME) * 0.001;
   
   if (t1-t0 < MinPeriod) {
      /* Next time draw more triangles to get longer elapsed time */
      Loops *= 2;
      return;
   }

   triRate = triCount / (t1-t0);
   pixelRate = triRate * Size;
   printf("Rate: %d tri in %gs = %g tri/s  %d pixels/s\n",
          triCount, t1-t0, triRate, (int)pixelRate);
   fflush(stdout);

   glutSwapBuffers();
}
예제 #16
0
파일: wave.cpp 프로젝트: jtanx/CITS3003-L
void idle()
{
   glUniform1f(timeParam, (GLfloat) glutGet(GLUT_ELAPSED_TIME));
   glutPostRedisplay();
}
예제 #17
0
void glutMainLoop(void)
{
   int idleiters;

   if(ReshapeFunc)
      ReshapeFunc(VarInfo.xres, VarInfo.yres);

   if(!DisplayFunc) {
      sprintf(exiterror, "Fatal Error: No Display Function registered\n");
      exit(0);
   }   

   for(;;) {
      ProcessTimers();

      if(Active)
	 ReceiveInput();
      else
	 if(VisiblePoll)
	    TestVisible();

      if(IdleFunc)
	 IdleFunc();
      
      if(VisibleSwitch) {
	 VisibleSwitch = 0;
	 if(VisibilityFunc)
	    VisibilityFunc(Visible ? GLUT_VISIBLE : GLUT_NOT_VISIBLE);
      }

      if(Resized) {
         SetVideoMode();
         CreateBuffer();

         if(!glFBDevMakeCurrent( Context, Buffer, Buffer )) {
            sprintf(exiterror, "Failure to Make Current\n");
            exit(0);
         }

         InitializeMenus();

         if(ReshapeFunc)
            ReshapeFunc(VarInfo.xres, VarInfo.yres);

         Redisplay = 1;
         Resized = 0;
      }

      if(Visible && Redisplay) {
	 Redisplay = 0;
         EraseCursor();
	 DisplayFunc();
	 if(!(DisplayMode & GLUT_DOUBLE)) {
	    if(ActiveMenu)
	       DrawMenus();
            DrawCursor();
	 }
         idleiters = 0;
      } else {
         /* we sleep if not receiving redisplays, and
            the main loop is running faster than 2khz */

         static int lasttime;
         int time = glutGet(GLUT_ELAPSED_TIME);
         if(time > lasttime) {
            if(idleiters >= 2)
               usleep(100);

            idleiters = 0;
            lasttime = time;
         }
         idleiters++;         
      }
   }
}
예제 #18
0
void display()	{
	n++;							// animation angle ++
	if(n == 360) n=0; // avoid infinity 
	changeView();

	GLfloat ebene[4][3]={ // Grundflaeche
		{-30.0f, 0.0f,-15.0f}, { 30.0f,0.0f,-15.0f},
		{ -30.0f, 0.0f,15.0f},{ 30.0f,0.0f, 15.0f}};
	GLfloat light_position1[]={ -20.0f, 20.0f, -20.0f, 0.0};

	glClearColor(1.0, 1.0, 1.0, 1.0);
	glClear(GL_DEPTH_BUFFER_BIT|GL_COLOR_BUFFER_BIT);
	float angle;

	glLightfv(GL_LIGHT0, GL_POSITION, light_position1);
	glDisable(GL_LIGHTING);

	// Skybox, Kugel ueber die aktuelle Szene, hellblau
	glPushMatrix();
		// bewegt sich mit der kamera
		glTranslatef(swipe_left_right, swipe_up_down, swipe_through_back);
		glColor4ub(15,170,255,100);
		glutSolidSphere(25,30,30);
	glPopMatrix();

	glPushMatrix();	
			// Bodenflaeche
			glTranslatef(0.0f, -3.0f, 0.0f); // nach unten verschoben
			glColor4ub(143, 163, 112, 255);
			glBegin(GL_QUAD_STRIP);
					glVertex3fv(ebene[0]);
					glVertex3fv(ebene[1]);
					glVertex3fv(ebene[2]);
					glVertex3fv(ebene[3]);
			glEnd();

			// Licht
			glEnable(GL_LIGHTING);
			glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

			// Teapot
			glPushMatrix();
					set_mat3();
					glTranslated(-2.5, 0.5, 3);
					glRotated(n,0,1,0);
					glutSolidTeapot(0.5);
			glPopMatrix();

			// Bank ausgeben
			// Bank2 ausgeben, Drehwinkel: ITMZ: 190 -> 910 % 360 = 190  ...
			glPushMatrix();
					glRotated(190, 0.0f, 1.0f, 0.0f);
					set_bank();
			glPopMatrix();

			glPushMatrix();
					glTranslated(3.0, 0.0, 0.0);	// (laengs, hoch, tief) = (x, y, z)
					glRotated(190, 0.0f, 1.0f, 0.0f);	// (winkel, x, y, z)
					set_bank();
			glPopMatrix();

				// Bank2 ausgeben
			glPushMatrix();
					glTranslated(-3.0, 0.0, 0.0);	// (laengs, hoch, tief)
					glRotated(190, 0.0f, 1.0f, 0.0f);
					set_bank();
			glPopMatrix();
			
			// Lampe
			glPushMatrix();
					glTranslated(-5,0,2);
					glRotated(45, 0,1,0);
					set_lamp();
			glPopMatrix();

			// *********** bewegliche Teile ******************
			glDisable(GL_LIGHTING);

			glPushMatrix(); 
					glRotated(90, 1.0, 0.0, 0.0);
					angle = glutGet(GLUT_ELAPSED_TIME)/1000.0f *15;
					glRotated(angle, 0.0, 0.0, 1.0);

					/*  Hier Drohe zusammensetzen und Parameter auswerten*/
					glTranslatef(0, -4, - drone_y_positon);
					set_drone();
			glPopMatrix(); // Time

	glPopMatrix(); // Gesamtszene

	glutSwapBuffers();
	glutPostRedisplay();
}
예제 #19
0
//------------------------------------------------------------
ofPoint ofAppGlutWindow::getScreenSize(){
	int width = glutGet(GLUT_SCREEN_WIDTH);
	int height = glutGet(GLUT_SCREEN_HEIGHT);
	return ofPoint(width, height,0);
}
예제 #20
0
파일: view.cpp 프로젝트: floe/surface-2.0
void display() {

	int curtime = glutGet( GLUT_ELAPSED_TIME );
	curframe++;

	if ((curtime - lasttime) >= 1000) {
		fps = (1000.0*(curframe-lastframe))/((double)(curtime-lasttime));
		lasttime  = curtime;
		lastframe = curframe;
		snprintf(buffer,sizeof(buffer),"FPS: %f",fps);
		printf("%s\n",buffer);
	}

	// clear buffers
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// move to origin
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glTranslatef(0,VIDEO_RES_Y,0);
	glScalef(1.0f, -1.0f, 1.0f);

	surface_get_image( s40, image );
	int bc = surface_get_blobs( s40, blobs );

	glEnable(GL_TEXTURE_2D);

	glBindTexture(GL_TEXTURE_2D, texture);
	glTexImage2D(GL_TEXTURE_2D, 0, 1, VIDEO_RES_X, VIDEO_RES_Y, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, image);

	glBegin(GL_TRIANGLE_FAN);
	glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
	glTexCoord2f(0, 0); glVertex3f(0,0,0);
	glTexCoord2f(1, 0); glVertex3f(VIDEO_RES_X,0,0);
	glTexCoord2f(1, 1); glVertex3f(VIDEO_RES_X,VIDEO_RES_Y,0);
	glTexCoord2f(0, 1); glVertex3f(0,VIDEO_RES_Y,0);
	glEnd();

	glDisable(GL_TEXTURE_2D);

	// green: tip
	glColor4f(0.0f, 1.0f, 0.0f, 1.0f);
	for (int i = 0; i < bc; i++) cross( blobs[i].pos_x/2, blobs[i].pos_y/2 );

	// red: centroid(?)
	glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
	for (int i = 0; i < bc; i++) cross( blobs[i].ctr_x/2, blobs[i].ctr_y/2 );

	// yellow: axis(?)
	/*glColor4f(1.0f, 1.0f, 0.0f, 1.0f);
	for (int i = 0; i < bc; i++) cross( (blobs[i].pos_x+blobs[i].axis_x)/2, (blobs[i].pos_y+blobs[i].axis_y)/2 );*/

	// blue: bbox
	glColor4f(0.0f, 0.0f, 1.0f, 1.0f);
	for (int i = 0; i < bc; i++) box( blobs[i].bb_pos_x/2, blobs[i].bb_pos_y/2, (blobs[i].bb_pos_x+blobs[i].bb_size_x)/2, (blobs[i].bb_pos_y+blobs[i].bb_size_y)/2 );

	// white: id
	glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
	char id_buf[64];
	for (int i = 0; i < bc; i++) {
		snprintf(id_buf,64,"%d",blobs[i].blob_id);
		output(blobs[i].ctr_x/2, blobs[i].ctr_y/2,id_buf);
	}

	output(20,20,buffer);
	// redraw
	glutSwapBuffers();
}
예제 #21
0
파일: main.cpp 프로젝트: shujing/3D-models
void display(void)
{
	int startTime=glutGet(GLUT_ELAPSED_TIME);
	int counter = 1;
	
	glClearDepth(1.0f);
    glDepthFunc(GL_LEQUAL);
    glEnable(GL_DEPTH_TEST);

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	//floor plane
	glBegin(GL_POLYGON);
	glColor3f(0.3, 0.73, 0.1);
	glVertex3f(-75, -0.02, 75);
	glVertex3f(75, -0.02, 75);
	glVertex3f(75, -0.02, -75);
	glVertex3f(-75, -0.02, -75);
	glEnd();

	//draw patches
	for(int i=0;i<9;i++)
	{
		for(int j=0;j<9;j++)
		{
			glPushMatrix();
			glTranslatef((i-4.5)*10+5, 0, (j-4.5)*10+5);
			glLoadName(counter);
			counter++;
			drawPatch();
			glPopMatrix();
		}
	}

	
	A0118626House(texSet);

	/*
	glPushMatrix();
	drawMyHouse(texSet);

	glTranslatef(10, 0, 0);
	drawMyHouse(texSet);

	glTranslatef(10, 0, 0);
	drawMyHouse(texSet);

	glTranslatef(10, 0, 0);
	drawMyHouse(texSet);

	glTranslatef(10, 0, 0);
	drawMyHouse(texSet);

	glPopMatrix();
	*/

	
	int endTime=glutGet(GLUT_ELAPSED_TIME);
	cout<<"Frame Rate: "<<(float)1000/(endTime-startTime)<<"\n";
	glFlush();
	glutSwapBuffers();

}
예제 #22
0
// Display a "Loading..." message on the screen
void RenderLoading()
{
	static PNG* pngLoading = &(GameData()->LoadingImage);
	pngLoading->displayAt(glutGet(GLUT_WINDOW_WIDTH) - pngLoading->getWidth(), glutGet(GLUT_WINDOW_HEIGHT) - pngLoading->getHeight(), 1);
}
예제 #23
0
void SetupGL() {
  // Parameter handling
  glShadeModel(GL_SMOOTH);

  // Accept fragment if it closer to the camera than the former one
  glDepthFunc(GL_LESS);
  // polygon rendering mode
  glEnable(GL_COLOR_MATERIAL);
  glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
  //glPolygonMode(GL_FRONT, GL_LINE);

  // Set up light source
  GLfloat light_position[] = {0.0, 30.0, -50.0, 0.0};

  glLightfv(GL_LIGHT0, GL_POSITION, light_position);
  glEnable(GL_LIGHTING);
  glEnable(GL_LIGHT0);

  // Black background
  glClearColor(0.0f, 0.0f, 0.0f, 1.0f);  // Black background

  // Register GLUT callbacks
  glutDisplayFunc(DisplayGL);
  glutKeyboardFunc(KeyboardGL);
  glutSpecialFunc(Specialkey);
  glutReshapeFunc(ReshapeGL);
  glutMouseFunc(MouseGL);
  glutMotionFunc(Mouse_active);

  // Call to the drawing function
  glutIdleFunc(Idle);
  last_time = glutGet(GLUT_ELAPSED_TIME);

  // Setup initial GL State
  glClearDepth(1.0f);

  // Init GLEW
  if (glewInit() != GLEW_OK) {
    std::cerr << "Failed to initialize GLEW." << std::endl;
    exit(-1);
  }

  // Setup initial GL State
  glClearDepth(1.0f);

  std::cout << "Initialise OpenGL: Success!" << std::endl;

  // VAO
  //        glGenVertexArrays(1, &VertexArrayID);
  //        glBindVertexArray(VertexArrayID);

  // Create and compile our GLSL program from the shaders
  programID_1 = LoadShaders("TransformVertexShader.vertexshader", "ColorFragmentShader.fragmentshader");

  // VBO -- VERTEX
  static const GLfloat g_vertex_buffer_data[] = {
      // Cube
      -1.0f, -1.0f, -1.0f,
      -1.0f, -1.0f, 1.0f,
      -1.0f, 1.0f,  1.0f,

      1.0f,  1.0f,  -1.0f,
      -1.0f, -1.0f, -1.0f,
      -1.0f, 1.0f,  -1.0f,

      1.0f,  -1.0f, 1.0f,
      -1.0f, -1.0f, -1.0f,
      1.0f,  -1.0f, -1.0f,

      1.0f,  1.0f,  -1.0f, 
      1.0f,  -1.0f, -1.0f,
      -1.0f, -1.0f, -1.0f, 

      -1.0f, -1.0f, -1.0f, 
      -1.0f, 1.0f,  1.0f, 
      -1.0f, 1.0f,  -1.0f, 

      1.0f,  -1.0f, 1.0f,
      -1.0f, -1.0f, 1.0f,
      -1.0f, -1.0f, -1.0f, 

      -1.0f, 1.0f,  1.0f, 
      -1.0f, -1.0f, 1.0f, 
      1.0f,  -1.0f, 1.0f, 

      1.0f,  1.0f,  1.0f, 
      1.0f, -1.0f, -1.0f,
      1.0f,  1.0f,  -1.0f,

      1.0f,  -1.0f, -1.0f,
      1.0f,  1.0f,  1.0f,
      1.0f,  -1.0f, 1.0f,

      1.0f,  1.0f,  1.0f,
      1.0f,  1.0f,  -1.0f,
      -1.0f, 1.0f,  -1.0f,

      1.0f,  1.0f,  1.0f, 
      -1.0f, 1.0f,  -1.0f,
      -1.0f, 1.0f,  1.0f,  

      1.0f,  1.0f,  1.0f,  
      -1.0f, 1.0f,  1.0f, 
      1.0f,  -1.0f, 1.0f,

      // Leg triangles
      // Top
      -0.5, 2, 1,
      0.5 , 2, 1,
      0, 2, -1,
      
      // Bottom
      -0.5, -2, 1,
      0.5, -2, 1,
      0.0, -2, -1,

      // Back
      -0.5, 2, 1,
      0.5, 2, 1,
      0.5, -2, 1,

      0.5, -2, 1,
      -0.5, -2, 1,
      -0.5, 2, 1,
      
      // Left
      0, 2, -1,
      -0.5, 2, 1,
      -0.5, -2, 1,

      -0.5, -2, 1,
      0, -2, -1,
      0, 2, -1,
      
      // Right
      0, 2, -1,
      0.5, 2, 1,
      0.5, -2, 1,

      0.5, -2, 1,
      0, -2, -1,
      0, 2, -1,

  };
  glGenBuffers(1, &vertexbuffer);
  glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
  glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);

  static const GLfloat g_color_buffer_data[] = {
      0.583f, 0.771f, 0.014f, 0.609f, 0.115f, 0.436f, 0.327f, 0.483f, 0.844f,
      0.822f, 0.569f, 0.201f, 0.435f, 0.602f, 0.223f, 0.310f, 0.747f, 0.185f,
      0.597f, 0.770f, 0.761f, 0.559f, 0.436f, 0.730f, 0.359f, 0.583f, 0.152f,
      0.483f, 0.596f, 0.789f, 0.559f, 0.861f, 0.639f, 0.195f, 0.548f, 0.859f,
      0.014f, 0.184f, 0.576f, 0.771f, 0.328f, 0.970f, 0.406f, 0.615f, 0.116f,
      0.676f, 0.977f, 0.133f, 0.971f, 0.572f, 0.833f, 0.140f, 0.616f, 0.489f,
      0.997f, 0.513f, 0.064f, 0.945f, 0.719f, 0.592f, 0.543f, 0.021f, 0.978f,
      0.279f, 0.317f, 0.505f, 0.167f, 0.620f, 0.077f, 0.347f, 0.857f, 0.137f,
      0.055f, 0.953f, 0.042f, 0.714f, 0.505f, 0.345f, 0.783f, 0.290f, 0.734f,
      0.722f, 0.645f, 0.174f, 0.302f, 0.455f, 0.848f, 0.225f, 0.587f, 0.040f,
      0.517f, 0.713f, 0.338f, 0.053f, 0.959f, 0.120f, 0.393f, 0.621f, 0.362f,
      0.673f, 0.211f, 0.457f, 0.820f, 0.883f, 0.371f, 0.982f, 0.099f, 0.879f,
      0.673f, 0.211f, 0.457f, 0.820f, 0.883f, 0.371f, 0.982f, 0.099f, 0.879f
  };
  glGenBuffers(1, &colorbuffer);
  glBindBuffer(GL_ARRAY_BUFFER, colorbuffer);
  glBufferData(GL_ARRAY_BUFFER, sizeof(g_color_buffer_data), g_color_buffer_data, GL_STATIC_DRAW);

  // Yellow
  static GLfloat g_yellow_buffer_data[24*3*3];
  for (int v = 0; v < 24*3; v++) {
    g_yellow_buffer_data[3*v+0] = 1.0f;
    g_yellow_buffer_data[3*v+1] = 1.0f;
    g_yellow_buffer_data[3*v+2] = 0.0f;
  }
  glGenBuffers(1, &yellowBuffer);
  glBindBuffer(GL_ARRAY_BUFFER, yellowBuffer);
  glBufferData(GL_ARRAY_BUFFER, sizeof(g_yellow_buffer_data), g_yellow_buffer_data, GL_STATIC_DRAW);

  // Red
  static GLfloat g_red_buffer_data[24*3*3];
  for (int v = 0; v < 24*3; v++) {
    g_red_buffer_data[3*v+0] = 1.0f;
    g_red_buffer_data[3*v+1] = 0.0f;
    g_red_buffer_data[3*v+2] = 0.0f;
  }
  glGenBuffers(1, &redBuffer);
  glBindBuffer(GL_ARRAY_BUFFER, redBuffer);
  glBufferData(GL_ARRAY_BUFFER, sizeof(g_red_buffer_data), g_red_buffer_data, GL_STATIC_DRAW);

  // Blue
  static GLfloat g_blue_buffer_data[24*3*3];
  for (int v = 0; v < 24*3; v++) {
    g_blue_buffer_data[3*v+0] = 0.0f;
    g_blue_buffer_data[3*v+1] = 0.0f;
    g_blue_buffer_data[3*v+2] = 1.0f;
  }
  glGenBuffers(1, &blueBuffer);
  glBindBuffer(GL_ARRAY_BUFFER, blueBuffer);
  glBufferData(GL_ARRAY_BUFFER, sizeof(g_blue_buffer_data), g_blue_buffer_data, GL_STATIC_DRAW);

  // Green
  static GLfloat g_green_buffer_data[24*3*3];
  for (int v = 0; v < 24*3; v++) {
    g_green_buffer_data[3*v+0] = 0.0f;
    g_green_buffer_data[3*v+1] = 1.0f;
    g_green_buffer_data[3*v+2] = 0.0f;
  }
  glGenBuffers(1, &greenBuffer);
  glBindBuffer(GL_ARRAY_BUFFER, greenBuffer);
  glBufferData(GL_ARRAY_BUFFER, sizeof(g_green_buffer_data), g_green_buffer_data, GL_STATIC_DRAW);
}
예제 #24
0
void Game::update()
//Function handling the update of the game.
{
	
	int now;
	int miliseconds;
	now = glutGet(GLUT_ELAPSED_TIME);
	miliseconds =  now - c_lastSong;
	
	if (miliseconds > 32600) {
		
		Jukebox::PlayBackground();
		c_lastSong = glutGet(GLUT_ELAPSED_TIME);
		
	}
	
	Game::getInstance().keyOperations();
	
	//Clear color and depth buffers:
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 

	//Clear the screen:
	glClearColor(1.0, 1.0, 1.0, 1.0); // Set the clear color to white
	glClear(GL_COLOR_BUFFER_BIT);     // clear the screen

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	//Draw the background:
	glEnable(GL_TEXTURE_2D);
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,GL_REPLACE);
	glBindTexture (GL_TEXTURE_2D, m_backgroundTexture);
	ImageLoader::rectangle(0,0, m_width, m_height);
	glDisable(GL_TEXTURE_2D);
	glFlush();
   
	//Update the HUD:
	HUDHandler::getInstance().displayHUD(); 

	if(!Game::c_running) {
		
	   	if(!Game::c_run) {

			//This will only call the main menu if the game has yet to be started.
			if (c_quit) {
				
				//If the user hits the escape key on the main menu, allow the quit
				//confirmation screen to be displayed instead of the main menu.
				return m_menu.quitScreen();
				
			} else {
				
				//If the user has not pushed the escape key, simply display the 
				//main menu screen for the user.
				return m_menu.mainMenu();

			}
			
		} else if (Game::c_quit) { 
		
			//This should display the quitScreen when ever the c_quit variable is 
			//set to true. TODO TEST THIS CODE.
			return m_menu.quitScreen();
		
		} else {
			
			//This will call the splash screen when ever the user pauses the game
			//using the space bar.
			return m_menu.splashScreen();

		}
	 
	}

	//Display and update the zombies:
	ZombieHandler::getInstance().display();
	ZombieHandler::getInstance().update();
	//Update the items:
	ItemHandler::getInstance().update();
	//Player display should be one of the very last, if not last.
	Player::getInstance().display();
	
}
예제 #25
0
int main(int argc, char* argv[])
{
    //-----------------------------------------------------------------------
    // INITIALIZATION
    //-----------------------------------------------------------------------

    printf ("\n");
    printf ("-----------------------------------\n");
    printf ("CHAI 3D\n");
    printf ("Demo: 11-effects\n");
    printf ("Copyright 2003-2009\n");
    printf ("-----------------------------------\n");
    printf ("\n\n");
    printf ("Keyboard Options:\n\n");
    printf ("[x] - Exit application\n");
    printf ("\n\n");

    // parse first arg to try and locate resources
    resourceRoot = string(argv[0]).substr(0,string(argv[0]).find_last_of("/\\")+1);


    //-----------------------------------------------------------------------
    // 3D - SCENEGRAPH
    //-----------------------------------------------------------------------

    // create a new world.
    world = new cWorld();

    // set the background color of the environment
    // the color is defined by its (R,G,B) components.
    world->setBackgroundColor(0.0, 0.0, 0.0);

    // create a camera and insert it into the virtual world
    camera = new cCamera(world);
    world->addChild(camera);

    // position and oriente the camera
    camera->set( cVector3d (3.0, 0.0, 0.0),    // camera position (eye)
                 cVector3d (0.0, 0.0, 0.0),    // lookat position (target)
                 cVector3d (0.0, 0.0, 1.0));   // direction of the "up" vector

    // set the near and far clipping planes of the camera
    // anything in front/behind these clipping planes will not be rendered
    camera->setClippingPlanes(0.01, 10.0);

    // enable higher quality rendering for transparent objects
    camera->enableMultipassTransparency(true);

    // create a light source and attach it to the camera
    light = new cLight(world);
    camera->addChild(light);                   // attach light to camera
    light->setEnabled(true);                   // enable light source
    light->setPos(cVector3d( 2.0, 0.5, 1.0));  // position the light source
    light->setDir(cVector3d(-2.0, 0.5, 1.0));  // define the direction of the light beam


    //-----------------------------------------------------------------------
    // 2D - WIDGETS
    //-----------------------------------------------------------------------

    // create a 2D bitmap logo
    logo = new cBitmap();

    // add logo to the front plane
    camera->m_front_2Dscene.addChild(logo);

    // load a "chai3d" bitmap image file
    bool fileload;
    fileload = logo->m_image.loadFromFile(RESOURCE_PATH("resources/images/chai3d.bmp"));
    if (!fileload)
    {
        #if defined(_MSVC)
        fileload = logo->m_image.loadFromFile("../../../bin/resources/images/chai3d.bmp");
        #endif
    }

    // position the logo at the bottom left of the screen (pixel coordinates)
    logo->setPos(10, 10, 0);

    // scale the logo along its horizontal and vertical axis
    logo->setZoomHV(0.4, 0.4);

    // here we replace all black pixels (0,0,0) of the logo bitmap
    // with transparent black pixels (0, 0, 0, 0). This allows us to make
    // the background of the logo look transparent.
    logo->m_image.replace(
                          cColorb(0, 0, 0),      // original RGB color
                          cColorb(0, 0, 0, 0)    // new RGBA color
                          );

    // enable transparency
    logo->enableTransparency(true);


    //-----------------------------------------------------------------------
    // HAPTIC DEVICES / TOOLS
    //-----------------------------------------------------------------------

    // create a haptic device handler
    handler = new cHapticDeviceHandler();

    // get access to the first available haptic device
    cGenericHapticDevice* hapticDevice;
    handler->getDevice(hapticDevice, 0);

    // retrieve information about the current haptic device
    cHapticDeviceInfo info;
    if (hapticDevice)
    {
        info = hapticDevice->getSpecifications();
    }

    // create a 3D tool and add it to the world
    tool = new cGeneric3dofPointer(world);
    world->addChild(tool);

    // connect the haptic device to the tool
    tool->setHapticDevice(hapticDevice);

    // initialize tool by connecting to haptic device
    tool->start();

    // map the physical workspace of the haptic device to a larger virtual workspace.
    tool->setWorkspaceRadius(1.0);

    // define a radius for the tool
    tool->setRadius(0.03);

    // read the scale factor between the physical workspace of the haptic
    // device and the virtual workspace defined for the tool
    double workspaceScaleFactor = tool->getWorkspaceScaleFactor();

    // define a maximum stiffness that can be handled by the current
    // haptic device. The value is scaled to take into account the
    // workspace scale factor
    double stiffnessMax = info.m_maxForceStiffness / workspaceScaleFactor;
    double forceMax = info.m_maxForce;

    // define the maximum damping factor that can be handled by the
    // current haptic device. The The value is scaled to take into account the
    // workspace scale factor
    double dampingMax = info.m_maxLinearDamping / workspaceScaleFactor; 


    //-----------------------------------------------------------------------
    // COMPOSE THE VIRTUAL SCENE
    //-----------------------------------------------------------------------

    // temp variable
    cGenericEffect* newEffect;


    /////////////////////////////////////////////////////////////////////////
    // OBJECT 0: "MAGNET"
    /////////////////////////////////////////////////////////////////////////

    // create a sphere and define its radius
    object0 = new cShapeSphere(0.3);

    // add object to world
    world->addChild(object0);

    // set the position of the object at the center of the world
    object0->setPos(0.0, -0.5, 0.0);

    // set graphic properties
    object0->m_texture = new cTexture2D();
    fileload = object0->m_texture->loadFromFile(RESOURCE_PATH("resources/images/chrome.bmp"));
    if (!fileload)
    {
        #if defined(_MSVC)
        fileload = object0->m_texture->loadFromFile("../../../bin/resources/images/chrome.bmp");
        #endif
    }
    if (!fileload)
    {
        printf("Error - Texture image failed to load correctly.\n");
        close();
        return (-1);
    }

    object0->m_texture->setSphericalMappingEnabled(true);
    object0->m_material.m_ambient.set(1.0, 1.0, 1.0);
    object0->m_material.m_diffuse.set(1.0, 1.0, 1.0);
    object0->m_material.m_specular.set(1.0, 1.0, 1.0);
    object0->m_material.setShininess(100);
    object0->setUseTexture(true);

    // set haptic properties
    object0->m_material.setStiffness(0.4 * stiffnessMax);
    object0->m_material.setMagnetMaxForce(0.4 * forceMax);
    object0->m_material.setMagnetMaxDistance(0.12);
    object0->m_material.setViscosity(0.2 * dampingMax);

    // create a haptic surface effect
    newEffect = new cEffectSurface(object0);
    object0->addEffect(newEffect);

    // create a haptic magnetic effect
    newEffect = new cEffectMagnet(object0);
    object0->addEffect(newEffect);


    /////////////////////////////////////////////////////////////////////////
    // OBJECT 1: "FLUID"
    ////////////////////////////////////////////////////////////////////////

    // create a sphere and define its radius
    object1 = new cShapeSphere(0.3);

    // add object to world
    world->addChild(object1);

    // set the position of the object at the center of the world
    object1->setPos(0.0, 0.5, 0.0);

    // set graphic properties
    object1->m_texture = new cTexture2D();
		fileload = object1->m_texture->loadFromFile(RESOURCE_PATH("resources/images/water.bmp"));
		if (!fileload)
		{
				#if defined(_MSVC)
				fileload = object1->m_texture->loadFromFile("../../../bin/resources/images/water.bmp");
				#endif
		}
		if (!fileload)
		{
				printf("Error - Texture image failed to load correctly.\n");
				close();
				return (-1);
		}

    object1->m_material.m_ambient.set(0.1, 0.1, 0.6, 0.5);
    object1->m_material.m_diffuse.set(0.3, 0.3, 0.9, 0.5);
    object1->m_material.m_specular.set(1.0, 1.0, 1.0, 0.5);
    object1->setTransparencyLevel(0.5);
    object1->setUseTexture(true);

    // set haptic properties
    object1->m_material.setViscosity(dampingMax);

    // create a haptic viscous effect
    newEffect = new cEffectViscosity(object1);
    object1->addEffect(newEffect);


    /////////////////////////////////////////////////////////////////////////
    // OBJECT 2: "STICK-SLIP"
    /////////////////////////////////////////////////////////////////////////

    // create a sphere and define its radius
    object2 = new cShapeSphere(0.3);

    // add object to world
    world->addChild(object2);

    // set the position of the object at the center of the world
    object2->setPos(0.0, 0.0, 0.5);

    // set graphic properties
    object2->m_texture = new cTexture2D();
    fileload = object2->m_texture->loadFromFile(RESOURCE_PATH("resources/images/stone.bmp"));
    if (!fileload)
    {
        #if defined(_MSVC)
        fileload = object2->m_texture->loadFromFile("../../../bin/resources/images/stone.bmp");
        #endif
    }
    if (!fileload)
    {
        printf("Error - Texture image failed to load correctly.\n");
        close();
        return (-1);
    }

    object2->m_material.m_ambient.set(0.1, 0.1, 0.6, 0.5);
    object2->m_material.m_diffuse.set(0.3, 0.3, 0.9, 0.5);
    object2->m_material.m_specular.set(1.0, 1.0, 1.0, 0.5);
    object2->setTransparencyLevel(0.5);
    object2->setUseTexture(true);

    // set haptic properties
    object2->m_material.setStickSlipForceMax(0.5 * forceMax);
    object2->m_material.setStickSlipStiffness(0.7 * stiffnessMax);

    // create a haptic stick-slip effect
    newEffect = new cEffectStickSlip(object2);
    object2->addEffect(newEffect);


    /////////////////////////////////////////////////////////////////////////
    // OBJECT 3: "VIBRATIONS"
    ////////////////////////////////////////////////////////////////////////

    // create a sphere and define its radius
    object3 = new cShapeSphere(0.3);

    // add object to world
    world->addChild(object3);

    // set the position of the object at the center of the world
    object3->setPos(0.0, 0.0, -0.5);

    // set graphic properties
    object3->m_texture = new cTexture2D();
    fileload = object3->m_texture->loadFromFile(RESOURCE_PATH("resources/images/plastic.bmp"));
    if (!fileload)
    {
        #if defined(_MSVC)
        fileload = object3->m_texture->loadFromFile("../../../bin/resources/images/plastic.bmp");
        #endif
    }
    if (!fileload)
    {
        printf("Error - Texture image failed to load correctly.\n");
        close();
        return (-1);
    }

    object3->m_texture->setSphericalMappingEnabled(true);
    object3->m_material.m_ambient.set(0.6, 0.1, 0.1, 0.5);
    object3->m_material.m_diffuse.set(0.9, 0.3, 0.3, 0.5);
    object3->m_material.m_specular.set(1.0, 1.0, 1.0, 0.5);
    object3->setTransparencyLevel(0.8);
    object3->setUseTexture(true);

    // set haptic properties
    object3->m_material.setVibrationFrequency(50);
    object3->m_material.setVibrationAmplitude(0.1 * forceMax);
    object3->m_material.setStiffness(0.1 * stiffnessMax);

    // create a haptic viscous effect
    newEffect = new cEffectVibration(object3);
    object3->addEffect(newEffect);

    newEffect = new cEffectSurface(object3);
    object3->addEffect(newEffect);


    //-----------------------------------------------------------------------
    // OPEN GL - WINDOW DISPLAY
    //-----------------------------------------------------------------------

    // initialize GLUT
    glutInit(&argc, argv);

    // retrieve the resolution of the computer display and estimate the position
    // of the GLUT window so that it is located at the center of the screen
    int screenW = glutGet(GLUT_SCREEN_WIDTH);
    int screenH = glutGet(GLUT_SCREEN_HEIGHT);
    int windowPosX = (screenW - WINDOW_SIZE_W) / 2;
    int windowPosY = (screenH - WINDOW_SIZE_H) / 2;

    // initialize the OpenGL GLUT window
    glutInitWindowPosition(windowPosX, windowPosY);
    glutInitWindowSize(WINDOW_SIZE_W, WINDOW_SIZE_H);
    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
    glutCreateWindow(argv[0]);
    glutDisplayFunc(updateGraphics);
    glutKeyboardFunc(keySelect);
    glutReshapeFunc(resizeWindow);
    glutSetWindowTitle("CHAI 3D");

    // create a mouse menu (right button)
    glutCreateMenu(menuSelect);
    glutAddMenuEntry("full screen", OPTION_FULLSCREEN);
    glutAddMenuEntry("window display", OPTION_WINDOWDISPLAY);
    glutAttachMenu(GLUT_RIGHT_BUTTON);


    //-----------------------------------------------------------------------
    // START SIMULATION
    //-----------------------------------------------------------------------

    // simulation in now running
    simulationRunning = true;

    // create a thread which starts the main haptics rendering loop
    cThread* hapticsThread = new cThread();
    hapticsThread->set(updateHaptics, CHAI_THREAD_PRIORITY_HAPTICS);

    // start the main graphics rendering loop
    glutMainLoop();

    // close everything
    close();

    // exit
    return (0);
}
예제 #26
0
/****Key Functions**********************************************************************/
void Game::key(unsigned char key, int x, int y)
//This function handles key input from the user for non-movement controls.
//TODO Determine if the x and y variables are needed for keyinput or not.
{
	
	c_keystates[key] = true;
	
    switch (key){
		
        case ' ' :
		
			//If the space bar is hit, the game first checks to see if the c_run
			//has changed from false yet. 
			if (Game::c_run == false) {
				
				//If c_run is still false, then we would start the game and set c_run
				//and c_running to true and allow the game to run.
				Game::c_run = !Game::c_run;
				Game::c_running = !Game::c_running;
				if (Game::c_quit) Game::c_quit = false;//If we had set the c_quit value to true, but then
				//started the game again, we make sure to reset c_quit to false so that it 
				//will not allow the user to hit space followed by enter to quit by mistake. 
				Jukebox::PlayBackground();//This should play the background song.
                Game::c_lastSong = glutGet(GLUT_ELAPSED_TIME);//This logs when the sound was started.
				
            } else {
				
				//If c_run has changed to true, then the game has been started and 
				//we simply deal with the c_running variable to decide upon displaying
				//the pause screen or allowing game play.
				Game::c_running = !Game::c_running;
				if (Game::c_quit) Game::c_quit = false;//If we had set the c_quit value to true, but then
				//started the game again, we make sure to reset c_quit to false so that it
				//will not allow the user to hit space followed by enter to quit by mistake.
				
            }
			
			break;
			
        case 'k':
			
			//If k is hit, check the status of the game and either allow an item use or do not allow item
			//use within the game. 
			if (Game::c_running) {
				
				//If the game is running, allow item use.
				ItemHandler::getInstance().iUse();
				//k will handle item use.
			
			}
				
			//Otherwise do nothing.
			break;
				
		case 'i':
			
			//If i is hit, check the status of the game and either allow an item swap or do not allow item
			//swap within the game. 
			if (Game::c_running) {
				
				//If the game is running, allow item swapping.
				//i will handle item swap.
				ItemHandler::getInstance().iSwitch();
			
			}

			//Otherwise do nothing.
			break;
				
		case 'j':
		
			//If j is hit, check the status of the game and either allow an attack or do not allow an
			//attack within the game. 
			if (Game::c_running) {	

				//If the game is running allow attacks.
				//j uses the currently equipted weapon to attack or do something else.
				Player::getInstance().attack();
			
			}
			
			//Otherwise do nothing.
			break;
		
		case 'u':
		
			//If u is hit, check the status of the game and either allow an weapon swap or do not allow
			//weapon swapping within the game.
			if (Game::c_running) {	

				//If the game is running allow weapon swapping.
				//u handles weapon swap.
				ItemHandler::getInstance().wSwitch();
			
			}

			//Otherwise do nothing.
			break;
		
		case 27:
		
		//27 refers to the escape key Ascii code. When the escape key is hit the game 
		//will check the c_quit variables state. If that state is false switch it to 
		//true, it if is true, switch it to false. The reason the code uses slightly
		//different style compared to other areas is due to the fact that for some 
		//reason the code using a normal expression of c_quit = !c_quit; seemed to
		//cause no change at all. 
		
			if (c_quit == false) {
				
				c_quit = true;
				
				if (DEBUG) {
					
					cout << "Debug-Game.cpp: c_quit set to true\n";
					
				}
				
			} else if (c_quit == true) {
				
				c_quit = false;
				
				if (DEBUG) {
					
					cout << "Debug-Game.cpp: c_quit set to false\n";
					
				}
			
			}
			
			break;

		case 13://13 is the enter key. This states that if the enter key is
		//pressed while the game is paused do the following.
			 
			if ((!Game::c_running) && (Game::c_quit)) {
				
				//If the game is paused allow the user to hit escape followed by enter
				//to quit the game.
				glutDestroyWindow(Game::c_windowID);//c_windowID should contain the windows
				//ID number so that we can destroy it.
				exit(0);//Exits the program.
			
			}
				
			//Otherwise do nothing.
			break;
		
		/*
		//TODO define the restart key and work out how to re-initialize all of the classes.
		case 'b'://b is only a temporary key to be used. When this key is pressed while the
		//game is paused and the quit confirmation screen is being displayed, allow call the
		//restart function.

			if ((!Game::c_running) && (c_quit)) {
				
				Game::getInstance().restartGame();
			
			}
			break;
		*/
	
    }

    //glutPostRedisplay();
	
}
예제 #27
0
int main(int argc, char* argv[])
{
    //-----------------------------------------------------------------------
    // INITIALIZATION
    //-----------------------------------------------------------------------

    printf ("\n");
    printf ("-----------------------------------\n");
    printf ("CHAI3D\n");
    printf ("Demo: 43-ODE-tool\n");
    printf ("Copyright 2003-2011\n");
    printf ("-----------------------------------\n");
    printf ("\n\n");
    printf ("Instructions:\n\n");
    printf ("- Use haptic device and user switch to manipulate cubes \n");
    printf ("\n\n");
    printf ("Keyboard Options:\n\n");
    printf ("[h] - Display help menu\n");;
    printf ("[1] - Enable gravity\n");
    printf ("[2] - Disable gravity\n");
    printf ("\n");
    printf ("[3] - decrease linear haptic gain\n");
    printf ("[4] - increase linear haptic gain\n");
    printf ("[5] - decrease angular haptic gain\n");
    printf ("[6] - increase angular haptic gain\n");
    printf ("\n");
    printf ("[7] - decrease linear stiffness\n");
    printf ("[8] - increase linear stiffness\n");
    printf ("[9] - decrease angular stiffness\n");
    printf ("[0] - increase angular stiffness\n");
    printf ("\n");
    printf ("[x] - Exit application\n");
    printf ("\n\n");

    // parse first arg to try and locate resources
    resourceRoot = string(argv[0]).substr(0,string(argv[0]).find_last_of("/\\")+1);


    //-----------------------------------------------------------------------
    // 3D - SCENEGRAPH
    //-----------------------------------------------------------------------

    // create a new world.
    world = new cWorld();

    // set the background color of the environment
    // the color is defined by its (R,G,B) components.
    world->setBackgroundColor(0.0, 0.0, 0.0);

    // create a camera and insert it into the virtual world
    camera = new cCamera(world);
    world->addChild(camera);

    // position and oriente the camera
    camera->set( cVector3d (3.0, 0.0, 0.3),    // camera position (eye)
                 cVector3d (0.0, 0.0, 0.0),    // lookat position (target)
                 cVector3d (0.0, 0.0, 1.0));   // direction of the "up" vector

    // set the near and far clipping planes of the camera
    // anything in front/behind these clipping planes will not be rendered
    camera->setClippingPlanes(0.01, 10.0);
    camera->setUseShadowCasting(false);

    // create a light source and attach it to the camera
    light = new cSpotLight(world);
    camera->addChild(light);                   // attach light to camera
    light->setEnabled(true);                   // enable light source
    light->setLocalPos(cVector3d( 0.0, 0.5, 0.0));  // position the light source
    light->setDir(cVector3d(-3.0,-0.5, 0.0));  // define the direction of the light beam
    light->m_ambient.set(0.6, 0.6, 0.6);
    light->m_diffuse.set(0.8, 0.8, 0.8);
    light->m_specular.set(0.8, 0.8, 0.8);


    frame = new cGenericObject();
    //world->addChild(frame);
    frame->setShowFrame(true);
    line = new cShapeLine(cVector3d(0,0,0), cVector3d(0,0,0));
    //world->addChild(line);

    //-----------------------------------------------------------------------
    // 2D - WIDGETS
    //-----------------------------------------------------------------------

    // create a 2D bitmap logo
    logo = new cBitmap();

    // add logo to the front plane
    camera->m_frontLayer->addChild(logo);

    // load a "chai3d" bitmap image file
    logo->setImage (NEW_CHAI3D_LOGO());

    // position the logo at the bottom left of the screen (pixel coordinates)
    logo->setLocalPos(10, 10, 0);

    // scale the logo along its horizontal and vertical axis
    logo->setZoom(0.25, 0.25);

    // here we replace all black pixels (0,0,0) of the logo bitmap
    // with transparent black pixels (0, 0, 0, 0). This allows us to make
    // the background of the logo look transparent.
    logo->m_image->setTransparentColor(0x00, 0x00, 0x00, 0x00);

    // enable transparency
    logo->setUseTransparency(true);


    //-----------------------------------------------------------------------
    // HAPTIC DEVICES / TOOLS
    //-----------------------------------------------------------------------

    // create a haptic device handler
    handler = new cHapticDeviceHandler();

    // get access to the first available haptic device
    handler->getDevice(hapticDevice, 0);

    // retrieve information about the current haptic device
    cHapticDeviceInfo info;
    if (hapticDevice)
    {
        info = hapticDevice->getSpecifications();
    }

    // read the scale factor between the physical workspace of the haptic
    // device and the virtual workspace defined for the tool
    workspaceScaleFactor = 1.5 / info.m_workspaceRadius;

    //-----------------------------------------------------------------------
    // COMPOSE THE VIRTUAL SCENE
    //-----------------------------------------------------------------------

    // create an ODE world to simulate dynamic bodies
    ODEWorld = new cODEWorld(world);

    // add ODE world as a node inside world
    world->addChild(ODEWorld);

    // set some gravity
    ODEWorld->setGravity(cVector3d(0.0, 0.0, -9.81));

    // create a new ODE object that is automatically added to the ODE world
    ODEBody0 = new cODEGenericBody(ODEWorld);
    ODEBody1 = new cODEGenericBody(ODEWorld);
    ODEBody2 = new cODEGenericBody(ODEWorld);

    // create a virtual mesh  that will be used for the geometry
    // representation of the dynamic body
    cMesh* object0 = new cMesh();
    cMesh* object1 = new cMesh();
    cMesh* object2 = new cMesh();

    // crate a cube mesh
    double boxSize = 0.4;
    createCube(object0, boxSize);
    createCube(object1, boxSize);
    createCube(object2, boxSize);

    // define some material properties for each cube
    cMaterial mat0, mat1, mat2;
    mat0.m_ambient.set(0.8, 0.1, 0.4);
    mat0.m_diffuse.set(1.0, 0.15, 0.5);
    mat0.m_specular.set(1.0, 0.2, 0.8);
    mat0.setDynamicFriction(0.8);
    mat0.setStaticFriction(0.8);
    object0->setMaterial(mat0);

    mat1.m_ambient.set(0.2, 0.6, 0.0);
    mat1.m_diffuse.set(0.2, 0.8, 0.0);
    mat1.m_specular.set(0.2, 1.0, 0.0);
    mat1.setDynamicFriction(0.8);
    mat1.setStaticFriction(0.8);
    object1->setMaterial(mat1);

    mat2.m_ambient.set(0.0, 0.2, 0.6);
    mat2.m_diffuse.set(0.0, 0.2, 0.8);
    mat2.m_specular.set(0.0, 0.2, 1.0);
    mat2.setDynamicFriction(0.8);
    mat2.setStaticFriction(0.8);
    object2->setMaterial(mat2);

    // add mesh to ODE object
    ODEBody0->setImageModel(object0);
    ODEBody1->setImageModel(object1);
    ODEBody2->setImageModel(object2);

    // create a dynamic model of the ODE object. Here we decide to use a box just like
    // the object mesh we just defined
    ODEBody0->createDynamicBox(boxSize, boxSize, boxSize);
    ODEBody1->createDynamicBox(boxSize, boxSize, boxSize, false, cVector3d(1,1,1));
    ODEBody2->createDynamicBox(boxSize, boxSize, boxSize);

    // define some mass properties for each cube
    ODEBody0->setMass(0.05);
    ODEBody1->setMass(0.05);
    ODEBody2->setMass(0.05);

    // set position of each cube
    cVector3d tmpvct;
    tmpvct = cVector3d(0.0,-0.6, -0.5);
    ODEBody0->setPosition(tmpvct);
    tmpvct = cVector3d(0.0, 0.6, -0.5);
    ODEBody1->setPosition(tmpvct);
    tmpvct = cVector3d(0.0, 0.0, -0.5);
    ODEBody2->setPosition(tmpvct);

    // rotate central cube of 45 degrees (just to show hoe this works!)
    cMatrix3d rot;
    rot.identity();
    rot.rotateAboutGlobalAxisRad(cVector3d(0,0,1), cDegToRad(45));
    ODEBody0->setRotation(rot);

    // we create 6 static walls to contains the 3 cubes within a limited workspace
    ODEGPlane0 = new cODEGenericBody(ODEWorld);
    ODEGPlane1 = new cODEGenericBody(ODEWorld);
    ODEGPlane2 = new cODEGenericBody(ODEWorld);
    ODEGPlane3 = new cODEGenericBody(ODEWorld);
    ODEGPlane4 = new cODEGenericBody(ODEWorld);
    ODEGPlane5 = new cODEGenericBody(ODEWorld);

    double size = 1.0;
    ODEGPlane0->createStaticPlane(cVector3d(0.0, 0.0,  2.0 *size), cVector3d(0.0, 0.0 ,-1.0));
    ODEGPlane1->createStaticPlane(cVector3d(0.0, 0.0, -size), cVector3d(0.0, 0.0 , 1.0));
    ODEGPlane2->createStaticPlane(cVector3d(0.0,  size, 0.0), cVector3d(0.0,-1.0, 0.0));
    ODEGPlane3->createStaticPlane(cVector3d(0.0, -size, 0.0), cVector3d(0.0, 1.0, 0.0));
    ODEGPlane4->createStaticPlane(cVector3d( size, 0.0, 0.0), cVector3d(-1.0,0.0, 0.0));
    ODEGPlane5->createStaticPlane(cVector3d(-0.8 * size, 0.0, 0.0), cVector3d( 1.0,0.0, 0.0));

    // create a virtual tool
    ODETool = new cODEGenericBody(ODEWorld);
    cMesh* objectTool = new cMesh();
    createCube(objectTool, boxSize);

    // define some material properties for each cube
    cMaterial matTool;
    matTool.m_ambient.set(0.4, 0.4, 0.4);
    matTool.m_diffuse.set(0.8, 0.8, 0.8);
    matTool.m_specular.set(1.0, 1.0, 1.0);
    matTool.setDynamicFriction(0.8);
    matTool.setStaticFriction(0.8);
    objectTool->setMaterial(matTool);

    // add mesh to ODE object
    ODETool->setImageModel(objectTool);
    ODETool->createDynamicBox(boxSize, boxSize, boxSize);

    // define some mass properties for each cube
    ODETool->setMass(0.01);
    dBodySetAngularDamping(ODETool->m_ode_body, 0.04);
    dBodySetLinearDamping(ODETool->m_ode_body, 0.04);


    //////////////////////////////////////////////////////////////////////////
    // Create some reflexion
    //////////////////////////////////////////////////////////////////////////

    // we create an intermediate node to which we will attach
    // a copy of the object located inside the world
    cGenericObject* reflexion = new cGenericObject();

    // set this object as a ghost node so that no haptic interactions or
    // collision detecting take place within the child nodes added to the
    // reflexion node.
    reflexion->setGhostEnabled(true);

    // add reflexion node to world
    world->addChild(reflexion);

    // turn off culling on each object (objects now get rendered on both sides)
    object0->setUseCulling(false, true);
    object1->setUseCulling(false, true);
    object2->setUseCulling(false, true);

    // create a symmetry rotation matrix (z-plane)
    cMatrix3d rotRefexion;
    rotRefexion.set(1.0, 0.0, 0.0,
                    0.0, 1.0, 0.0,
                    0.0, 0.0, -1.0);
    reflexion->setLocalRot(rotRefexion);
    reflexion->setLocalPos(0.0, 0.0, -2.005);

    // add objects to the world
    reflexion->addChild(ODEWorld);

    //////////////////////////////////////////////////////////////////////////
    // Create a Ground
    //////////////////////////////////////////////////////////////////////////

    // create mesh to model ground surface
    cMesh* ground = new cMesh();
    world->addChild(ground);

    // create 4 vertices (one at each corner)
    double groundSize = 2.0;
    int vertices0 = ground->newVertex(-groundSize, -groundSize, 0.0);
    int vertices1 = ground->newVertex( groundSize, -groundSize, 0.0);
    int vertices2 = ground->newVertex( groundSize,  groundSize, 0.0);
    int vertices3 = ground->newVertex(-groundSize,  groundSize, 0.0);

    // compose surface with 2 triangles
    ground->newTriangle(vertices0, vertices1, vertices2);
    ground->newTriangle(vertices0, vertices2, vertices3);

    // compute surface normals
    ground->computeAllNormals();

    // position ground at the right level
    ground->setLocalPos(0.0, 0.0, -1.0);

    // define some material properties and apply to mesh
    cMaterial matGround;
    matGround.setDynamicFriction(0.7);
    matGround.setStaticFriction(1.0);
    matGround.m_ambient.set(0.0, 0.0, 0.0);
    matGround.m_diffuse.set(0.0, 0.0, 0.0);
    matGround.m_specular.set(0.0, 0.0, 0.0);
    ground->setMaterial(matGround);

    // enable and set transparency level of ground
    ground->setTransparencyLevel(0.7);
    ground->setUseTransparency(true);


    //-----------------------------------------------------------------------
    // OPEN GL - WINDOW DISPLAY
    //-----------------------------------------------------------------------

    // initialize GLUT
    glutInit(&argc, argv);

    // retrieve the resolution of the computer display and estimate the position
    // of the GLUT window so that it is located at the center of the screen
    int screenW = glutGet(GLUT_SCREEN_WIDTH);
    int screenH = glutGet(GLUT_SCREEN_HEIGHT);
    int windowPosX = (screenW - WINDOW_SIZE_W) / 2;
    int windowPosY = (screenH - WINDOW_SIZE_H) / 2;

    // initialize the OpenGL GLUT window
    glutInitWindowPosition(windowPosX, windowPosY);
    glutInitWindowSize(WINDOW_SIZE_W, WINDOW_SIZE_H);
    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
    glutCreateWindow(argv[0]);
    glutDisplayFunc(updateGraphics);
    glutKeyboardFunc(keySelect);
    glutReshapeFunc(resizeWindow);
    glutSetWindowTitle("CHAI3D");

    // create a mouse menu (right button)
    glutCreateMenu(menuSelect);
    glutAddMenuEntry("full screen", OPTION_FULLSCREEN);
    glutAddMenuEntry("window display", OPTION_WINDOWDISPLAY);
    glutAttachMenu(GLUT_RIGHT_BUTTON);


    //-----------------------------------------------------------------------
    // START SIMULATION
    //-----------------------------------------------------------------------

    // simulation in now running
    simulationRunning = true;

    // create a thread which starts the main haptics rendering loop
    cThread* hapticsThread = new cThread();
    hapticsThread->start(updateHaptics, CTHREAD_PRIORITY_HAPTICS);

    // start the main graphics rendering loop
    glutTimerFunc(30, graphicsTimer, 0);
    glutMainLoop();

    // close everything
    close();

    // exit
    return (0);
    }
예제 #28
0
void displayUISettings()
{
    // getting window dimensions
    GLshort w=glutGet(GLUT_WINDOW_WIDTH);
    uiS.height=glutGet(GLUT_WINDOW_HEIGHT);
    GLshort percUnitW = w/100;
    GLshort percUnitH = uiS.height/100;

    glDisable(GL_DEPTH_TEST);
    glClear(GL_DEPTH_BUFFER_BIT);

    glMatrixMode(GL_PROJECTION);
    glPushMatrix(); //to prepare for return to 3D
    glLoadIdentity();
    gluOrtho2D(0,w,0,uiS.height);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    //UI background 20% of screen gap from edges
    glColor3f(1,1,1); //white
    glBegin(GL_QUADS);
        glVertex2s(percUnitW*20,percUnitH*20);
        glVertex2s(w-percUnitW*20,percUnitH*20);
        glVertex2s(w-percUnitW*20,uiS.height-percUnitH*20);
        glVertex2s(percUnitW*20,uiS.height-percUnitH*20);
    glEnd();

    glColor3f(0,0,1);
    displayText("SETTINGS:", percUnitW*22, percUnitH*78, 'l');

    //draw chosen colour if not random
    if(!tmpState.colourRand){
        uiS.chosenClr[0] = percUnitW*25;
        uiS.chosenClr[1] = percUnitH*55;
        glColor3fv(tmpState.colour);
        glBegin(GL_QUADS);
            glVertex2sv(uiS.chosenClr);
            glVertex2s(uiS.chosenClr[0]+20, uiS.chosenClr[1]);
            glVertex2s(uiS.chosenClr[0]+20, uiS.chosenClr[1]+20);
            glVertex2s(uiS.chosenClr[0], uiS.chosenClr[1]+20);
        glEnd();
        displayText("Chosen Colour", uiS.chosenClr[0]+25, uiS.chosenClr[1]+2, 'm');
    }

    //for colourpicker triangle
    drawColourPicker(percUnitW, percUnitH);
    //check box for selection of random colour
    uiS.randClr[0]=percUnitW*35;
    uiS.randClr[1]=percUnitH*55;
    drawCheckBox(uiS.randClr[0],uiS.randClr[1],"Random Colour");
    //if random colour selected draw cross
    if(tmpState.colourRand){
        drawCheck(uiS.randClr[0],uiS.randClr[1]);
    }

    //for selection of angle: draw a box then distribute evenly within 9 circles of radius 10, in 3 rows of 3, filled in for chosen angle
    drawAnglePresets(percUnitW, percUnitH);

    //check box for selection of random angle
    uiS.randAng[0] = percUnitW*60;
    uiS.randAng[1] = percUnitH*55;
    drawCheckBox(uiS.randAng[0], uiS.randAng[1] ,"Random Angle");

    //slider bar for selection of lift charge/intial velocity
    uiS.velocityL[0]= percUnitW*23;
    uiS.velocityL[1]= percUnitH*42;
    uiS.velocityR[0]= percUnitW*65;
    uiS.velocityR[1]= percUnitH*42;
    snprintf(uiS.velocityMnTxt, 6, "%4.1f", tmpState.velocityMin);
    snprintf(uiS.velocityMxTxt, 6, "%4.1f", tmpState.velocityMax);
    displayText("Lift Charge giving initial velocity in m/s:", uiS.velocityL[0]-20, uiS.velocityL[1]+15, 'm');
    drawSlider(uiS.velocityL, uiS.velocityR);
    displayText(uiS.velocityMnTxt, uiS.velocityL[0]-30, uiS.velocityL[1]-4, 'm');
    displayText(uiS.velocityMxTxt, uiS.velocityR[0]+5, uiS.velocityR[1]-4, 'm');

    //x coords of chosen velocity determined by (chosenValue - minValue)*((xRight - xLeft)/(maxValue-minValue)) + xLeft
    uiS.velocityChX = ((tmpState.velocityCh - tmpState.velocityMin)*(((float)uiS.velocityR[0]-(float)uiS.velocityL[0])/(tmpState.velocityMax-tmpState.velocityMin))+(float)uiS.velocityL[0]);
    drawMarker(uiS.velocityChX, uiS.velocityL[1]);
    snprintf(uiS.velocityChTxt, 6, "%3.1f", tmpState.velocityCh);
    displayText(uiS.velocityChTxt, uiS.velocityChX-10, uiS.velocityL[1]-17, 'm');

    //slider bar for selection of fuser timer
    uiS.fuseL[0]= percUnitW*23;
    uiS.fuseL[1]= percUnitH*32;
    uiS.fuseR[0]= percUnitW*65;
    uiS.fuseR[1]= percUnitH*32;
    snprintf(uiS.fuseMnTxt, 6, "%5.1f", tmpState.fuseMin);
    snprintf(uiS.fuseMxTxt, 6, "%5.1f", tmpState.fuseMax);
    displayText("Fuse timer from launch to explosion in milliseconds:", uiS.fuseL[0]-20, uiS.fuseL[1]+15, 'm');
    drawSlider(uiS.fuseL, uiS.fuseR);
    displayText(uiS.fuseMnTxt, uiS.fuseL[0]-40, uiS.fuseL[1]-4, 'm');
    displayText(uiS.fuseMxTxt, uiS.fuseR[0]+5, uiS.fuseR[1]-4, 'm');

    //x coords of chosen fuse determined by (chosenValue - minValue)*((xRight - xLeft)/(maxValue-minValue)) + xLeft
    uiS.fuseChX = ((tmpState.fuseCh - tmpState.fuseMin)*(((float)uiS.fuseR[0]-(float)uiS.fuseL[0])/(tmpState.fuseMax-tmpState.fuseMin))+(float)uiS.fuseL[0]);
    drawMarker(uiS.fuseChX, uiS.fuseL[1]);
    snprintf(uiS.fuseChTxt, 6, "%5.1f", tmpState.fuseCh);
    displayText(uiS.fuseChTxt, uiS.fuseChX-10, uiS.fuseL[1]-17, 'm');


    //save button
    uiS.saveBL[0] = percUnitW*70;
    uiS.saveBL[1] = percUnitH*31;
    uiS.saveTR[0] = percUnitW*79;
    uiS.saveTR[1] = percUnitH*39;
    glColor3f(0, 0.5, 0);
    glBegin(GL_QUADS);
        glVertex2sv(uiS.saveBL);
        glVertex2s(uiS.saveTR[0], uiS.saveBL[1]);
        glVertex2sv(uiS.saveTR);
        glVertex2s(uiS.saveBL[0], uiS.saveTR[1]);
    glEnd();
    displayText("Save", uiS.saveBL[0]+5, uiS.saveBL[1]+5,'l');
    //underline S
    glLineWidth(2);
    glBegin(GL_LINES);
        glVertex2s(uiS.saveBL[0]+6,uiS.saveBL[1]+3);
        glVertex2s(uiS.saveBL[0]+18,uiS.saveBL[1]+3);
    glEnd();
    glLineWidth(1);

    //cancel button
    uiS.cancelBL[0] = percUnitW*70;
    uiS.cancelBL[1] = percUnitH*22;
    uiS.cancelTR[0] = percUnitW*79;
    uiS.cancelTR[1] = percUnitH*30;
    glColor3f(0.6, 0, 0);
    glBegin(GL_QUADS);
        glVertex2sv(uiS.cancelBL);
        glVertex2s(uiS.cancelTR[0], uiS.cancelBL[1]);
        glVertex2sv(uiS.cancelTR);
        glVertex2s(uiS.cancelBL[0], uiS.cancelTR[1]);
    glEnd();
    displayText("Cancel", uiS.cancelBL[0]+5, uiS.cancelBL[1]+5,'l');
    //underline C
    glLineWidth(2);
    glBegin(GL_LINES);
        glVertex2s(uiS.cancelBL[0]+6,uiS.cancelBL[1]+3);
        glVertex2s(uiS.cancelBL[0]+18,uiS.cancelBL[1]+3);
    glEnd();
    glLineWidth(1);

    // returning to 3D
    glMatrixMode(GL_PROJECTION);
    glPopMatrix();
    glMatrixMode(GL_MODELVIEW);

    glEnable(GL_DEPTH_TEST);
}
예제 #29
0
파일: timer.cpp 프로젝트: CPutz/Mandelbrot
void Timer::stop() {
	if( this->isRunning ) {
		this->tStop = glutGet( GLUT_ELAPSED_TIME );
    }
    this->isRunning = false;
}
예제 #30
0
void GLCanvas::keyboard(unsigned char key, int x, int y) {
	args->raytracing_animation = false;
	switch (key) {
		// RAYTRACING STUFF
	case 'r':	case 'R':
	{
		// animate raytracing of the scene
		args->gather_indirect=false;
		args->raytracing_animation = !args->raytracing_animation;
		if (args->raytracing_animation) {
			// time the animation
			rendering_time = std::chrono::duration_cast<std::chrono::microseconds>(
				std::chrono::system_clock::now().time_since_epoch()).count();
			
			raytracing_skip = 1; //my_max(args->width,args->height) / 10;
			raytracing_x = 0;
			raytracing_y = 0;
			display(); // clear out any old rendering
			printf ("raytracing animation started, press 'R' to stop\n");
		} else {
			printf ("raytracing animation stopped, press 'R' to start\n");		
			// Print time to render
			rendering_time = std::chrono::duration_cast<std::chrono::microseconds>(
				std::chrono::system_clock::now().time_since_epoch()).count() 
				- rendering_time;
			std::cout << "Rendering completed in " << rendering_time/1000000.0
					<< " seconds." << std::endl;
		}
		break;
	}
	case 't':	case 'T': {
		// visualize the ray tree for the pixel at the current mouse position
		int i = x;
		int j = glutGet(GLUT_WINDOW_HEIGHT)-y;
		RayTree::Activate();
		raytracing_skip = 1;
		//TraceRay(i,j);
		//photon_mapping->setupVBOs();
		//photon_mapping->initializeVBOs();
		std::cout << "about to trace photons " << std::endl;
		TracePhoton(i,j);
		//photon_mapping->drawVBOs();
		//RayTree::drawVBOs();
		RayTree::Deactivate();
		// redraw
		std::cout << "about to call setup VBOs after trace photons" << std::endl;
		RayTree::setupVBOs();
		radiosity->setupVBOs();
		photon_mapping->setupVBOs();


		glutPostRedisplay();
		break; 
	}

	case 'l':	case 'L': { 
		// toggle photon rendering
		args->render_photons = !args->render_photons;
		glutPostRedisplay();
		break; }
	case 'k':	case 'K': { 
		// toggle photon rendering
		args->render_kdtree = !args->render_kdtree;
		glutPostRedisplay();
		break; }
	case 'p':	case 'P': { 
		// toggle photon rendering
		photon_mapping->TracePhotons();
		
		// TODO: remove
		//photon_mapping->printKDTree();
		
		photon_mapping->setupVBOs();
		RayTree::setupVBOs();
		glutPostRedisplay();
		break; }
	case 'g':	case 'G': { 
		args->gather_indirect = true;
		args->raytracing_animation = !args->raytracing_animation;
		if (args->raytracing_animation) {
			// time the animation
			rendering_time = 
				std::chrono::duration_cast<std::chrono::microseconds>(
				std::chrono::system_clock::now().time_since_epoch()).count();

			raytracing_x = 0;
			raytracing_y = 0;
			raytracing_skip = 1;//my_max(args->width,args->height) / 10;

			display(); // clear out any old rendering
			printf ("photon mapping animation started, press 'G' to stop\n");
		} else {
			printf ("photon mapping animation stopped, press 'G' to start\n");		
			// Print time to render
			rendering_time = std::chrono::duration_cast<std::chrono::microseconds>(
				std::chrono::system_clock::now().time_since_epoch()).count() 
				- rendering_time;
			std::cout << "Rendering stopped after " << rendering_time/1000000.0 
					<< " seconds." << std::endl;
		}
		break; 
	}
		
	case 's': case 'S':
	{
		// subdivide the mesh for radiosity
		radiosity->Cleanup();
		radiosity->getMesh()->Subdivision();
		radiosity->Reset();
		radiosity->setupVBOs();
		glutPostRedisplay();
		break;
	}
		// VISUALIZATIONS
	case 'w':	case 'W':
	{
		// render wireframe mode
		args->wireframe = !args->wireframe;
		glutPostRedisplay();
		break;
	}
	case 'v': case 'V':
	{
		std::cout << "RENDER_MATERIALS is the only mode\n";
		break;
	}
	case 'q':	case 'Q':
	{
		// quit
		delete GLCanvas::photon_mapping;
		delete GLCanvas::raytracer;
		delete GLCanvas::radiosity;
		delete GLCanvas::mesh;
		exit(0);
		break;
	}
	default:
		printf("UNKNOWN KEYBOARD INPUT	'%c'\n", key);
	}
}