Beispiel #1
0
void sdlgl_update(hwrbitmap d,s16 x,s16 y,s16 w,s16 h) {
  SDL_GL_SwapBuffers();
}
Beispiel #2
0
	void Graphics::FlipBuffers()
	{
		SDL_GL_SwapBuffers();
	}
Beispiel #3
0
int RunGLTest( int argc, char* argv[],
               int logo, int logocursor, int slowly, int bpp, float gamma, int noframe, int fsaa, int sync, int accel )
{
	int i;
	int rgb_size[3];
	int w = 640;
	int h = 480;
	int done = 0;
	int frames;
	Uint32 start_time, this_time;
        float color[8][3]= {{ 1.0,  1.0,  0.0}, 
			    { 1.0,  0.0,  0.0},
			    { 0.0,  0.0,  0.0},
			    { 0.0,  1.0,  0.0},
			    { 0.0,  1.0,  1.0},
			    { 1.0,  1.0,  1.0},
			    { 1.0,  0.0,  1.0},
			    { 0.0,  0.0,  1.0}};
	float cube[8][3]= {{ 0.5,  0.5, -0.5}, 
			   { 0.5, -0.5, -0.5},
			   {-0.5, -0.5, -0.5},
			   {-0.5,  0.5, -0.5},
			   {-0.5,  0.5,  0.5},
			   { 0.5,  0.5,  0.5},
			   { 0.5, -0.5,  0.5},
			   {-0.5, -0.5,  0.5}};
	Uint32 video_flags;
	int value;

	if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) {
		fprintf(stderr,"Couldn't initialize SDL: %s\n",SDL_GetError());
		exit( 1 );
	}

	/* See if we should detect the display depth */
	if ( bpp == 0 ) {
		if ( SDL_GetVideoInfo()->vfmt->BitsPerPixel <= 8 ) {
			bpp = 8;
		} else {
			bpp = 16;  /* More doesn't seem to work */
		}
	}

	/* Set the flags we want to use for setting the video mode */
	if ( logo && USE_DEPRECATED_OPENGLBLIT ) {
		video_flags = SDL_OPENGLBLIT;
	} else {
		video_flags = SDL_OPENGL;
	}
	for ( i=1; argv[i]; ++i ) {
		if ( strcmp(argv[i], "-fullscreen") == 0 ) {
			video_flags |= SDL_FULLSCREEN;
		}
	}

        if (noframe) {
           video_flags |= SDL_NOFRAME;
        }

	/* Initialize the display */
	switch (bpp) {
	    case 8:
		rgb_size[0] = 3;
		rgb_size[1] = 3;
		rgb_size[2] = 2;
		break;
	    case 15:
	    case 16:
		rgb_size[0] = 5;
		rgb_size[1] = 5;
		rgb_size[2] = 5;
		break;
            default:
		rgb_size[0] = 8;
		rgb_size[1] = 8;
		rgb_size[2] = 8;
		break;
	}
	SDL_GL_SetAttribute( SDL_GL_RED_SIZE, rgb_size[0] );
	SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, rgb_size[1] );
	SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, rgb_size[2] );
	SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );
	SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
	if ( fsaa ) {
		SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, 1 );
		SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, fsaa );
	}
	if ( accel ) {
		SDL_GL_SetAttribute( SDL_GL_ACCELERATED_VISUAL, 1 );
	}
	if ( sync ) {
		SDL_GL_SetAttribute( SDL_GL_SWAP_CONTROL, 1 );
	} else {
		SDL_GL_SetAttribute( SDL_GL_SWAP_CONTROL, 0 );
	}
	if ( SDL_SetVideoMode( w, h, bpp, video_flags ) == NULL ) {
		fprintf(stderr, "Couldn't set GL mode: %s\n", SDL_GetError());
		SDL_Quit();
		exit(1);
	}

	printf("Screen BPP: %d\n", SDL_GetVideoSurface()->format->BitsPerPixel);
	printf("\n");
	printf( "Vendor     : %s\n", glGetString( GL_VENDOR ) );
	printf( "Renderer   : %s\n", glGetString( GL_RENDERER ) );
	printf( "Version    : %s\n", glGetString( GL_VERSION ) );
	printf( "Extensions : %s\n", glGetString( GL_EXTENSIONS ) );
	printf("\n");

	SDL_GL_GetAttribute( SDL_GL_RED_SIZE, &value );
	printf( "SDL_GL_RED_SIZE: requested %d, got %d\n", rgb_size[0],value);
	SDL_GL_GetAttribute( SDL_GL_GREEN_SIZE, &value );
	printf( "SDL_GL_GREEN_SIZE: requested %d, got %d\n", rgb_size[1],value);
	SDL_GL_GetAttribute( SDL_GL_BLUE_SIZE, &value );
	printf( "SDL_GL_BLUE_SIZE: requested %d, got %d\n", rgb_size[2],value);
	SDL_GL_GetAttribute( SDL_GL_DEPTH_SIZE, &value );
	printf( "SDL_GL_DEPTH_SIZE: requested %d, got %d\n", bpp, value );
	SDL_GL_GetAttribute( SDL_GL_DOUBLEBUFFER, &value );
	printf( "SDL_GL_DOUBLEBUFFER: requested 1, got %d\n", value );
	if ( fsaa ) {
		SDL_GL_GetAttribute( SDL_GL_MULTISAMPLEBUFFERS, &value );
		printf("SDL_GL_MULTISAMPLEBUFFERS: requested 1, got %d\n", value );
		SDL_GL_GetAttribute( SDL_GL_MULTISAMPLESAMPLES, &value );
		printf("SDL_GL_MULTISAMPLESAMPLES: requested %d, got %d\n", fsaa, value );
	}
	if ( accel ) {
		SDL_GL_GetAttribute( SDL_GL_ACCELERATED_VISUAL, &value );
		printf( "SDL_GL_ACCELERATED_VISUAL: requested 1, got %d\n", value );
	}
	if ( sync ) {
		SDL_GL_GetAttribute( SDL_GL_SWAP_CONTROL, &value );
		printf( "SDL_GL_SWAP_CONTROL: requested 1, got %d\n", value );
	}

	/* Set the window manager title bar */
	SDL_WM_SetCaption( "SDL GL test", "testgl" );

	/* Set the gamma for the window */
	if ( gamma != 0.0 ) {
		SDL_SetGamma(gamma, gamma, gamma);
	}

	glViewport( 0, 0, w, h );
	glMatrixMode( GL_PROJECTION );
	glLoadIdentity( );

	glOrtho( -2.0, 2.0, -2.0, 2.0, -20.0, 20.0 );

	glMatrixMode( GL_MODELVIEW );
	glLoadIdentity( );

	glEnable(GL_DEPTH_TEST);

	glDepthFunc(GL_LESS);

	glShadeModel(GL_SMOOTH);

	/* Loop until done. */
	start_time = SDL_GetTicks();
	frames = 0;
	while( !done ) {
		GLenum gl_error;
		char* sdl_error;
		SDL_Event event;

		/* Do our drawing, too. */
		glClearColor( 0.0, 0.0, 0.0, 1.0 );
		glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		glBegin( GL_QUADS );

#ifdef SHADED_CUBE
			glColor3fv(color[0]);
			glVertex3fv(cube[0]);
			glColor3fv(color[1]);
			glVertex3fv(cube[1]);
			glColor3fv(color[2]);
			glVertex3fv(cube[2]);
			glColor3fv(color[3]);
			glVertex3fv(cube[3]);
			
			glColor3fv(color[3]);
			glVertex3fv(cube[3]);
			glColor3fv(color[4]);
			glVertex3fv(cube[4]);
			glColor3fv(color[7]);
			glVertex3fv(cube[7]);
			glColor3fv(color[2]);
			glVertex3fv(cube[2]);
			
			glColor3fv(color[0]);
			glVertex3fv(cube[0]);
			glColor3fv(color[5]);
			glVertex3fv(cube[5]);
			glColor3fv(color[6]);
			glVertex3fv(cube[6]);
			glColor3fv(color[1]);
			glVertex3fv(cube[1]);
			
			glColor3fv(color[5]);
			glVertex3fv(cube[5]);
			glColor3fv(color[4]);
			glVertex3fv(cube[4]);
			glColor3fv(color[7]);
			glVertex3fv(cube[7]);
			glColor3fv(color[6]);
			glVertex3fv(cube[6]);

			glColor3fv(color[5]);
			glVertex3fv(cube[5]);
			glColor3fv(color[0]);
			glVertex3fv(cube[0]);
			glColor3fv(color[3]);
			glVertex3fv(cube[3]);
			glColor3fv(color[4]);
			glVertex3fv(cube[4]);

			glColor3fv(color[6]);
			glVertex3fv(cube[6]);
			glColor3fv(color[1]);
			glVertex3fv(cube[1]);
			glColor3fv(color[2]);
			glVertex3fv(cube[2]);
			glColor3fv(color[7]);
			glVertex3fv(cube[7]);
#else /* flat cube */
			glColor3f(1.0, 0.0, 0.0);
			glVertex3fv(cube[0]);
			glVertex3fv(cube[1]);
			glVertex3fv(cube[2]);
			glVertex3fv(cube[3]);
			
			glColor3f(0.0, 1.0, 0.0);
			glVertex3fv(cube[3]);
			glVertex3fv(cube[4]);
			glVertex3fv(cube[7]);
			glVertex3fv(cube[2]);
			
			glColor3f(0.0, 0.0, 1.0);
			glVertex3fv(cube[0]);
			glVertex3fv(cube[5]);
			glVertex3fv(cube[6]);
			glVertex3fv(cube[1]);
			
			glColor3f(0.0, 1.0, 1.0);
			glVertex3fv(cube[5]);
			glVertex3fv(cube[4]);
			glVertex3fv(cube[7]);
			glVertex3fv(cube[6]);

			glColor3f(1.0, 1.0, 0.0);
			glVertex3fv(cube[5]);
			glVertex3fv(cube[0]);
			glVertex3fv(cube[3]);
			glVertex3fv(cube[4]);

			glColor3f(1.0, 0.0, 1.0);
			glVertex3fv(cube[6]);
			glVertex3fv(cube[1]);
			glVertex3fv(cube[2]);
			glVertex3fv(cube[7]);
#endif /* SHADED_CUBE */

		glEnd( );
		
		glMatrixMode(GL_MODELVIEW);
		glRotatef(5.0, 1.0, 1.0, 1.0);

		/* Draw 2D logo onto the 3D display */
		if ( logo ) {
			if ( USE_DEPRECATED_OPENGLBLIT ) {
				DrawLogoBlit();
			} else {
				DrawLogoTexture();
			}
		}
		if ( logocursor ) {
			DrawLogoCursor();
		}

		SDL_GL_SwapBuffers( );

		/* Check for error conditions. */
		gl_error = glGetError( );

		if( gl_error != GL_NO_ERROR ) {
			fprintf( stderr, "testgl: OpenGL error: %d\n", gl_error );
		}

		sdl_error = SDL_GetError( );

		if( sdl_error[0] != '\0' ) {
			fprintf(stderr, "testgl: SDL error '%s'\n", sdl_error);
			SDL_ClearError();
		}

		/* Allow the user to see what's happening */
		if ( slowly ) {
			SDL_Delay( 20 );
		}

		/* Check if there's a pending event. */
		while( SDL_PollEvent( &event ) ) {
			done = HandleEvent(&event);
		}
		++frames;
	}

	/* Print out the frames per second */
	this_time = SDL_GetTicks();
	if ( this_time != start_time ) {
		printf("%2.2f FPS\n",
			((float)frames/(this_time-start_time))*1000.0);
	}

	if ( global_image ) {
	   	SDL_FreeSurface(global_image);
		global_image = NULL;
	}
	if ( global_texture ) {
		glDeleteTextures( 1, &global_texture );
		global_texture = 0;
	}
	if ( cursor_texture ) {
		glDeleteTextures( 1, &cursor_texture );
		cursor_texture = 0;
	}

	/* Destroy our GL context, etc. */
	SDL_Quit( );
	return(0);
}
Beispiel #4
0
bool menu_run(Settings *settings) {
  assert(settings != NULL);

  SDL_EnableKeyRepeat(10000 / WINDOW_FRAMERATE, 10000 / WINDOW_FRAMERATE);

  glClearColor(0, 0, 0, 1);

  int level_set_index = 0, theme_index = 0;

  menu_preload();

  // default settings
  if(settings->first_run) {
    settings->play_with_computer = true;
    settings->volume = 100;
    strncpy(settings->level_set, s_sets_names[level_set_index], LIM_STR_LEN);
    settings->level = 1;
    strncpy(settings->theme, s_themes_names[theme_index], LIM_STR_LEN);
    settings->ball_speed = BALL_DEFAULT_SPEED;
  }

  Timer timer = timer_new(WINDOW_FRAMERATE);

  const bool* events = NULL;
  bool leave = false;
  bool vol_updated = false;
  while(!leave) {
    events = event_poll();

    if(events[EVENT_QUIT] || events[EVENT_KEY_ESCAPE]) {
      return false;
    }

    if(events[EVENT_KEY_UP]) {
      if(s_focus == 0) {
        s_focus = __MENU_LABEL_LAST - 1;
      } else {
        s_focus--;
      }

      audio_play(SOUND_TOCK);
    }

    if(events[EVENT_KEY_DOWN]) {
      s_focus++;
      audio_play(SOUND_TOCK);

      if(s_focus == __MENU_LABEL_LAST) {
        s_focus = 0;
      }
    }

    if(events[EVENT_KEY_LEFT]) {
      bool action = true;

      switch(s_focus) {
      case LABEL_SECOND_PLAYER:
        settings->play_with_computer = !settings->play_with_computer;
        break;

      case LABEL_SOUND_VOLUME:
        settings->volume -= 10;
        if(settings->volume < 0) {
          settings->volume = 0;
          action = false;
        } else {
          vol_updated = true;
        }
        break;

      case LABEL_LEVEL_SET:
        s_level_set_index--;
        if(s_level_set_index < 0) {
          s_level_set_index = s_sets_names_length - 1;
        }
        settings->level = 1;
        break;

      case LABEL_LEVEL:
        (settings->level)--;
        if(settings->level <= 0) {
          settings->level = s_sets_levels[s_level_set_index];
        }
        break;

      case LABEL_THEME:
        s_theme_index--;
        if(s_theme_index < 0) {
          s_theme_index = s_themes_names_length - 1;
        }
        break;

      case LABEL_BALL_SPEED:
        (settings->ball_speed)--;
        if(settings->ball_speed < BALL_MIN_SPEED) {
          settings->ball_speed = BALL_MAX_SPEED;
        }
        break;

      default:
        action = false;
        break;
      }

      if(action) {
        audio_play(SOUND_TICK);
      }
    }

    if(events[EVENT_KEY_RIGHT]) {
      bool action = true;

      switch(s_focus) {
      case LABEL_SECOND_PLAYER:
        settings->play_with_computer = !settings->play_with_computer;
        break;

      case LABEL_SOUND_VOLUME:
        settings->volume += 10;
        if(settings->volume > 100) {
          settings->volume = 100;
          action = false;
        } else {
          vol_updated = true;
        }
        break;

      case LABEL_LEVEL_SET:
        s_level_set_index++;
        if(s_level_set_index >= s_sets_names_length) {
          s_level_set_index = 0;
        }
        settings->level = 1;
        break;

      case LABEL_LEVEL:
        (settings->level)++;
        if(settings->level > s_sets_levels[s_level_set_index]) {
          settings->level = 1;
        }
        break;

      case LABEL_THEME:
        s_theme_index++;
        if(s_theme_index >= s_themes_names_length) {
          s_theme_index = 0;
        }
        break;

      case LABEL_BALL_SPEED:
        (settings->ball_speed)++;
        if(settings->ball_speed > BALL_MAX_SPEED) {
          settings->ball_speed = BALL_MIN_SPEED;
        }
        break;

      default:
        action = false;
        break;
      }

      if(action) {
        audio_play(SOUND_TICK);
      }
    }

    if(events[EVENT_KEY_ENTER]) {
      if(s_focus == LABEL_QUIT) {
        return false;
      } else {
        leave = true;
      }
    }

    if(vol_updated) {
      audio_set_volume(settings->volume);
      vol_updated = false;
    }

    glClear(GL_COLOR_BUFFER_BIT);

    menu_display(settings);

    SDL_GL_SwapBuffers();

    timer_sleep(&timer);
  }

  strncpy(settings->level_set, s_sets_names[s_level_set_index], LIM_STR_LEN);
  strncpy(settings->theme, s_themes_names[s_theme_index], LIM_STR_LEN);

  settings->first_run = false;

  return true;
}
Beispiel #5
0
int main(int argc, char *argv[])
{
    SDL_Surface *screen;
    if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) {
        printf("Unable to initialize SDL: %s\n", SDL_GetError());
        return 1;
    }

    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
    screen = SDL_SetVideoMode( 640, 480, 24, SDL_OPENGL );
    if ( !screen ) {
        printf("Unable to set video mode: %s\n", SDL_GetError());
        return 1;
    }
    
    glClearColor( 0, 0, 0, 0 );
    glClear( GL_COLOR_BUFFER_BIT );

    // Create a texture

    GLuint texture;
    glGenTextures( 1, &texture );
    glBindTexture( GL_TEXTURE_2D, texture );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
    GLubyte textureData[16*16*4];
    for (int x = 0; x < 16; x++) {
      for (int y = 0; y < 16; y++) {
        *((int*)&textureData[(x*16 + y) * 4]) = x*16 + ((y*16) << 8);
      }
    }
    glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, 16, 16, 0, 
                  GL_RGBA, GL_UNSIGNED_BYTE, textureData );

    // Create a second texture

    GLuint texture2;
    glGenTextures( 1, &texture2 );
    glBindTexture( GL_TEXTURE_2D, texture2 );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
    GLubyte texture2Data[] = { 0xff,    0,    0, 0xff,
                                  0, 0xff,    0, 0xaa,
                                  0,    0, 0xff, 0x55,
                               0x80, 0x90, 0x70,    0 };
    glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, 2, 2, 0,
                  GL_RGBA, GL_UNSIGNED_BYTE, texture2Data );
    
    // BEGIN

#if USE_GLEW
    glewInit();
#endif

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    // original: glFrustum(-0.6435469817188064, 0.6435469817188064 ,-0.48266022190470925, 0.48266022190470925 ,0.5400000214576721, 2048);
    glFrustum(-0.6435469817188064, 0.1435469817188064 ,-0.48266022190470925, 0.88266022190470925 ,0.5400000214576721, 2048);
    glRotatef(-30, 1, 1, 1);
    //GLfloat pm[] = { 1.372136116027832, 0, 0, 0, 0, 0.7910231351852417, 0, 0, -0.6352481842041016, 0.29297152161598206, -1.0005275011062622, -1, 0, 0, -1.080284833908081, 0 };
    //glLoadMatrixf(pm);

    glMatrixMode(GL_MODELVIEW);
    GLfloat matrixData[] = { -1, 0, 0, 0,
                              0, 0,-1, 0,
                              0, 1, 0, 0,
                              0, 0, 0, 1 };
    glLoadMatrixf(matrixData);
    //glTranslated(-512,-512,-527); // XXX this should be uncommented, but if it is then nothing is shown

    glEnable(GL_CULL_FACE);
    glEnable(GL_DEPTH_TEST);

    glClear(GL_DEPTH_BUFFER_BIT);

    glEnableClientState(GL_NORMAL_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

    glActiveTexture(GL_TEXTURE0);

    glEnableClientState(GL_VERTEX_ARRAY);

    GLuint arrayBuffer, elementBuffer;
    glGenBuffers(1, &arrayBuffer);
    glGenBuffers(1, &elementBuffer);

    GLubyte arrayData[] = {
/*
[0, 0,   0, 67] ==>  128 float
[0, 0, 128, 67] ==>  256 float
[0, 0,   0, 68] ==>  512 float
[0, 0, 128, 68] ==> 1024 float

[vertex x        ] [vertex y         ] [vertex z         ] [nr]                [texture u        ] [texture v        ] [lm u   ] [lm v   ] [color r,g,b,a    ] */
  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,  68,  11,   10,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128, //  0
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,  68,  23,   20,   0,   0,   0,   0,   0,  67,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128, //  1
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,  35,   30,   0,   0,   0,   0,   0,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  2
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,  68,  47,   40,   0,   0,   0,   0,   0,   0,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  3
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,  68,  51,   50,   0,   0,   0,   0,   0,  67,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128, //  4
  0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,  68,  64,   60,   0,   0,   0,   0, 128,  67,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128, //  5
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,  68,  70,   70,   0,   0,   0,   0, 128,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  6
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,  89,   80,   0,   0,   0,   0,   0,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  7
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,  68,  94,   90,   0,   0,   0,   0,   0,   0,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  8
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,  20,   10,   0,   0,   0,   0,   0,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  9
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,  68,  31,   20,   0,   0,   0,   0,   0,  67,   0,   0, 128,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 10
  0,   0,   0,   0,   0,   0, 128,  68,   0,   0,   0,  68,  42,   30,   0,   0,   0,   0,   0,   0,   0,   0, 128,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 11
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,  53,   40,   0,   0,   0,   0,   0,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 12
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,  68,  64,   50,   0,   0,   0,   0, 128,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 13
  0,   0, 128,  68,   0,   0, 128,  68,   0,   0,   0,  68,  75,   60,   0,   0,   0,   0, 128,  67,   0,   0, 128,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 14
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,  68,  86,   70,   0,   0,   0,   0,   0,  67,   0,   0, 128,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 15

  0,   0,   0,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128
    };
    assert(sizeof(arrayData) == 1408);
    glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(arrayData), arrayData, GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    GLushort elementData[] = { 1, 2, 0, 2, 3, 0, 5, 6, 4, 6, 7, 4, 9, 10, 8, 10, 11, 8, 13, 14, 12, 14, 15, 12 };
    assert(sizeof(elementData) == 48);

    glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer);

    // sauer vertex data is apparently 0-12: V3F, 12: N1B, 16-24: T2F, 24-28: T2S, 28-32: C4B
    glVertexPointer(3, GL_FLOAT, 32, (void*)0); // all these apply to the ARRAY_BUFFER that is bound
    glTexCoordPointer(2, GL_FLOAT, 32, (void*)16);
    glClientActiveTexture(GL_TEXTURE1); // XXX seems to be ignored in native build
    glTexCoordPointer(2, GL_SHORT, 32, (void*)24);
    glClientActiveTexture(GL_TEXTURE0); // likely not needed, it is a cleanup
    glNormalPointer(GL_BYTE, 32, (void*)12);
    glColorPointer(4, GL_UNSIGNED_BYTE, 32, (void*)28);

    glBindTexture(GL_TEXTURE_2D, texture); // diffuse?
    glActiveTexture(GL_TEXTURE0);
    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, texture2); // lightmap?
    glActiveTexture(GL_TEXTURE0);

    GLint ok;

    const char *vertexShader = "uniform vec4 texgenscroll;\n"
                               "void main(void)\n"
                               "{\n"
                               "    gl_Position = ftransform();\n"
                               "    gl_TexCoord[0].xy = gl_MultiTexCoord0.xy/10000.0 + (0.001*texgenscroll.xy) + gl_Normal.xy;\n" // added /100 here
                               "    gl_TexCoord[1].xy = gl_MultiTexCoord1.xy/100.0 * 3.051851e-05;\n"
                               "}\n";
    const char *fragmentShader = "uniform vec4 colorparams;\n"
                                 "uniform sampler2D diffusemap, lightmap;\n"
                                 "void main(void)\n"
                                 "{\n"
                                 "    vec4 diffuse = texture2D(diffusemap, gl_TexCoord[0].xy);\n"
                                 "    vec4 lm = texture2D(lightmap, gl_TexCoord[1].xy);\n"
                                 "    diffuse *= colorparams;\n"
                                 "    gl_FragColor = diffuse * lm;\n"
                                 "}\n";

    GLuint vs = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vs, 1, &vertexShader, NULL);
    glCompileShader(vs);
    glGetShaderiv(vs, GL_COMPILE_STATUS, &ok);
    assert(ok);

    GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fs, 1, &fragmentShader, NULL);
    glCompileShader(fs);
    glGetShaderiv(fs, GL_COMPILE_STATUS, &ok);
    assert(ok);

    GLuint program = glCreateProgram();

    glAttachShader(program, vs);
    glAttachShader(program, fs);
    glLinkProgram(program);
    glGetProgramiv(program, GL_LINK_STATUS, &ok);
    assert(ok);

    glUseProgram(program);

    GLint lightmapLocation = glGetUniformLocation(program, "lightmap");
    assert(lightmapLocation >= 0);
    glUniform1i(lightmapLocation, 1); // sampler2D? Is it the texture unit?

    GLint diffusemapLocation = glGetUniformLocation(program, "diffusemap");
    assert(diffusemapLocation >= 0);
    glUniform1i(diffusemapLocation, 0);

    GLint texgenscrollLocation = glGetUniformLocation(program, "texgenscroll");
    assert(texgenscrollLocation >= 0);

    GLint colorparamsLocation = glGetUniformLocation(program, "colorparams");
    assert(colorparamsLocation >= 0);

    GLfloat texgenscrollData[] = { 0, 0, 0, 0 };
    glUniform4fv(texgenscrollLocation, 1, texgenscrollData);

    GLfloat colorparamsData[] = { 2, 2, 2, 1 };
    glUniform4fv(colorparamsLocation, 1, colorparamsData);

    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)&elementData[12/sizeof(GLushort)]);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)&elementData[ 0/sizeof(GLushort)]);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)&elementData[24/sizeof(GLushort)]);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)&elementData[36/sizeof(GLushort)]);

    // END

    SDL_GL_SwapBuffers();

  
#ifndef __EMSCRIPTEN__
    SDL_Delay(1500);
#endif

    SDL_Quit();
    
    return 0;
}
Beispiel #6
0
int main(int /*argc*/, char** /*argv*/)
{
    // Init SDL
    if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
    {
        printf("Could not initialise SDL\n");
        return -1;
    }
    
    // Init OpenGL
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
    SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
    
    const SDL_VideoInfo* vi = SDL_GetVideoInfo();

    bool presentationMode = false;

    int width, height;
    SDL_Surface* screen = 0;
    
    if (presentationMode)
    {
        width = vi->current_w;
        height = vi->current_h;
        screen = SDL_SetVideoMode(width, height, 0, SDL_OPENGL|SDL_FULLSCREEN);
    }
    else
    {    
        width = vi->current_w - 20;
        height = vi->current_h - 80;
        screen = SDL_SetVideoMode(width, height, 0, SDL_OPENGL);
    }
    
    if (!screen)
    {
        printf("Could not initialise SDL opengl\n");
        return -1;
    }
    
    SDL_WM_SetCaption("Recast Demo", 0);
    
    if (!imguiRenderGLInit("DroidSans.ttf"))
    {
        printf("Could not init GUI renderer.\n");
        SDL_Quit();
        return -1;
    }
    
    float t = 0.0f;
    float timeAcc = 0.0f;
    Uint32 lastTime = SDL_GetTicks();
    int mx = 0, my = 0;
    float rx = 45;
    float ry = -45;
    float moveW = 0, moveS = 0, moveA = 0, moveD = 0;
    float camx = 0, camy = 0, camz = 0, camr = 1000;
    float origrx = 0, origry = 0;
    int origx = 0, origy = 0;
    float scrollZoom = 0;
    bool rotate = false;
    bool movedDuringRotate = false;
    float rays[3], raye[3]; 
    bool mouseOverMenu = false;
    bool showMenu = !presentationMode;
    bool showLog = false;
    bool showDebugMode = true;
    bool showTools = true;
    bool showMaps = false;
    bool showLevels = false;
    bool showSample = false;
    bool showTestCases = false;

    int propScroll = 0;
    int logScroll = 0;
    int toolsScroll = 0;
    int debugScroll = 0;
    
    char sampleName[64] = "Choose Sample..."; 
    
    FileList maps;
    char mapName[128] = "Choose Map...";

    FileList files;
    char meshName[128] = "Choose Tile...";
    
    float mpos[3] = {0,0,0};
    bool mposSet = false;
    
    SlideShow slideShow;
    slideShow.init("slides/");
    
    InputGeom* geom = 0;
    Sample* sample = 0;
    TestCase* test = 0;

    BuildContext ctx;
    
    glEnable(GL_CULL_FACE);
    
    float fogCol[4] = { 0.32f,0.25f,0.25f,1 };
    glEnable(GL_FOG);
    glFogi(GL_FOG_MODE, GL_LINEAR);
    glFogf(GL_FOG_START, camr*0.2f);
    glFogf(GL_FOG_END, camr*1.25f);
    glFogfv(GL_FOG_COLOR, fogCol);
    
    glDepthFunc(GL_LEQUAL);
    
    glEnable(GL_POINT_SMOOTH);
    glEnable(GL_LINE_SMOOTH);
    
    bool done = false;
    while(!done)
    {
        // Handle input events.
        int mscroll = 0;
        bool processHitTest = false;
        bool processHitTestShift = false;
        SDL_Event event;
        
        while (SDL_PollEvent(&event))
        {
            switch (event.type)
            {
                case SDL_KEYDOWN:
                    // Handle any key presses here.
                    if (event.key.keysym.sym == SDLK_ESCAPE)
                    {
                        done = true;
                    }
                    else if (event.key.keysym.sym == SDLK_t)
                    {
                        showLevels = false;
                        showSample = false;
                        showTestCases = true;
                        scanDirectory("Tests", ".txt", files);
                    }
                    else if (event.key.keysym.sym == SDLK_TAB)
                    {
                        showMenu = !showMenu;
                    }
                    else if (event.key.keysym.sym == SDLK_SPACE)
                    {
                        if (sample)
                            sample->handleToggle();
                    }
                    else if (event.key.keysym.sym == SDLK_1)
                    {
                        if (sample)
                            sample->handleStep();
                    }
                    else if (event.key.keysym.sym == SDLK_9)
                    {
                        if (geom)
                            geom->save("geomset.txt");
                    }
                    else if (event.key.keysym.sym == SDLK_0)
                    {
                        delete geom;
                        geom = new InputGeom;
                        if (!geom || !geom->load(&ctx, "geomset.txt"))
                        {
                            delete geom;
                            geom = 0;
                            
                            showLog = true;
                            logScroll = 0;
                            ctx.dumpLog("Geom load log %s:", meshName);
                        }
                        if (sample && geom)
                        {
                            sample->handleMeshChanged(geom);
                        }
                            
                        if (geom || sample)
                        {
                            const float* bmin = 0;
                            const float* bmax = 0;
                            if (sample)
                            {
                                bmin = sample->getBoundsMin();
                                bmax = sample->getBoundsMax();
                            }
                            else if (geom)
                            {
                                bmin = geom->getMeshBoundsMin();
                                bmax = geom->getMeshBoundsMax();
                            }
                            // Reset camera and fog to match the mesh bounds.
                            if (bmin && bmax)
                            {
                                camr = sqrtf(rcSqr(bmax[0]-bmin[0]) +
                                             rcSqr(bmax[1]-bmin[1]) +
                                             rcSqr(bmax[2]-bmin[2])) / 2;
                                camx = (bmax[0] + bmin[0]) / 2 + camr;
                                camy = (bmax[1] + bmin[1]) / 2 + camr;
                                camz = (bmax[2] + bmin[2]) / 2 + camr;
                                camr *= 3;
                            }
                            rx = 45;
                            ry = -45;
                            glFogf(GL_FOG_START, camr*0.2f);
                            glFogf(GL_FOG_END, camr*1.25f);
                        }
                    }
                    else if (event.key.keysym.sym == SDLK_RIGHT)
                    {
                        slideShow.nextSlide();
                    }
                    else if (event.key.keysym.sym == SDLK_LEFT)
                    {
                        slideShow.prevSlide();
                    }
                    break;
                    
                case SDL_MOUSEBUTTONDOWN:
                    if (event.button.button == SDL_BUTTON_RIGHT)
                    {
                        if (!mouseOverMenu)
                        {
                            // Rotate view
                            rotate = true;
                            movedDuringRotate = false;
                            origx = mx;
                            origy = my;
                            origrx = rx;
                            origry = ry;
                        }
                    }    
                    else if (event.button.button == SDL_BUTTON_WHEELUP)
                    {
                        if (mouseOverMenu)
                            mscroll--;
                        else
                            scrollZoom -= 1.0f;
                    }
                    else if (event.button.button == SDL_BUTTON_WHEELDOWN)
                    {
                        if (mouseOverMenu)
                            mscroll++;
                        else
                            scrollZoom += 1.0f;
                    }
                    break;
                    
                case SDL_MOUSEBUTTONUP:
                    // Handle mouse clicks here.
                    if (event.button.button == SDL_BUTTON_RIGHT)
                    {
                        rotate = false;
                        if (!mouseOverMenu)
                        {
                            if (!movedDuringRotate)
                            {
                                processHitTest = true;
                                processHitTestShift = true;
                            }
                        }
                    }
                    else if (event.button.button == SDL_BUTTON_LEFT)
                    {
                        if (!mouseOverMenu)
                        {
                            processHitTest = true;
                            processHitTestShift = (SDL_GetModState() & KMOD_SHIFT) ? true : false;
                        }
                    }
                    
                    break;
                    
                case SDL_MOUSEMOTION:
                    mx = event.motion.x;
                    my = height-1 - event.motion.y;
                    if (rotate)
                    {
                        int dx = mx - origx;
                        int dy = my - origy;
                        rx = origrx - dy*0.25f;
                        ry = origry + dx*0.25f;
                        if (dx*dx+dy*dy > 3*3)
                            movedDuringRotate = true;
                    }
                    break;
                    
                case SDL_QUIT:
                    done = true;
                    break;
                    
                default:
                    break;
            }
        }

        unsigned char mbut = 0;
        if (SDL_GetMouseState(0,0) & SDL_BUTTON_LMASK)
            mbut |= IMGUI_MBUT_LEFT;
        if (SDL_GetMouseState(0,0) & SDL_BUTTON_RMASK)
            mbut |= IMGUI_MBUT_RIGHT;
        
        Uint32    time = SDL_GetTicks();
        float    dt = (time - lastTime) / 1000.0f;
        lastTime = time;
        
        t += dt;


        // Hit test mesh.
        if (processHitTest && geom && sample)
        {
            float t;
            TimeVal t0 = getPerfTime();
            bool hit = geom->raycastMesh(rays, raye, t);
            TimeVal t1 = getPerfTime();
            
            printf("raycast() %.4fms\n", getPerfDeltaTimeUsec(t0,t1)/1000.0f);
            
            if (hit)
            {
                if (SDL_GetModState() & KMOD_CTRL)
                {
                    // Marker
                    mposSet = true;
                    mpos[0] = rays[0] + (raye[0] - rays[0])*t;
                    mpos[1] = rays[1] + (raye[1] - rays[1])*t;
                    mpos[2] = rays[2] + (raye[2] - rays[2])*t;
                }
                else
                {
                    float pos[3];
                    pos[0] = rays[0] + (raye[0] - rays[0])*t;
                    pos[1] = rays[1] + (raye[1] - rays[1])*t;
                    pos[2] = rays[2] + (raye[2] - rays[2])*t;
                    sample->handleClick(rays, pos, processHitTestShift);
                }
            }
            else
            {
                if (SDL_GetModState() & KMOD_CTRL)
                {
                    // Marker
                    mposSet = false;
                }
            }
        }
        
        // Update sample simulation.
        const float SIM_RATE = 20;
        const float DELTA_TIME = 1.0f/SIM_RATE;
        timeAcc = rcClamp(timeAcc+dt, -1.0f, 1.0f);
        int simIter = 0;
        while (timeAcc > DELTA_TIME)
        {
            timeAcc -= DELTA_TIME;
            if (simIter < 5)
            {
                if (sample)
                    sample->handleUpdate(DELTA_TIME);
            }
            simIter++;
        }
         
        // Update and render
        glViewport(0, 0, width, height);
        glClearColor(0.3f, 0.3f, 0.32f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glDisable(GL_TEXTURE_2D);
        
        // Render 3d
        glEnable(GL_DEPTH_TEST);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        gluPerspective(50.0f, (float)width/(float)height, 1.0f, camr);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        glRotatef(rx,1,0,0);
        glRotatef(ry,0,1,0);
        glTranslatef(-camx, -camy, -camz);
        
        // Get hit ray position and direction.
        GLdouble proj[16];
        GLdouble model[16];
        GLint view[4];
        glGetDoublev(GL_PROJECTION_MATRIX, proj);
        glGetDoublev(GL_MODELVIEW_MATRIX, model);
        glGetIntegerv(GL_VIEWPORT, view);
        GLdouble x, y, z;
        gluUnProject(mx, my, 0.0f, model, proj, view, &x, &y, &z);
        rays[0] = (float)x; rays[1] = (float)y; rays[2] = (float)z;
        gluUnProject(mx, my, 1.0f, model, proj, view, &x, &y, &z);
        raye[0] = (float)x; raye[1] = (float)y; raye[2] = (float)z;
        
        // Handle keyboard movement.
        Uint8* keystate = SDL_GetKeyState(NULL);
        moveW = rcClamp(moveW + dt * 4 * (keystate[SDLK_w] ? 1 : -1), 0.0f, 1.0f);
        moveS = rcClamp(moveS + dt * 4 * (keystate[SDLK_s] ? 1 : -1), 0.0f, 1.0f);
        moveA = rcClamp(moveA + dt * 4 * (keystate[SDLK_a] ? 1 : -1), 0.0f, 1.0f);
        moveD = rcClamp(moveD + dt * 4 * (keystate[SDLK_d] ? 1 : -1), 0.0f, 1.0f);
        
        float keybSpeed = 22.0f;
        if (SDL_GetModState() & KMOD_SHIFT)
            keybSpeed *= 4.0f;
        
        float movex = (moveD - moveA) * keybSpeed * dt;
        float movey = (moveS - moveW) * keybSpeed * dt;
        
        movey += scrollZoom * 2.0f;
        scrollZoom = 0;
        
        camx += movex * (float)model[0];
        camy += movex * (float)model[4];
        camz += movex * (float)model[8];
        
        camx += movey * (float)model[2];
        camy += movey * (float)model[6];
        camz += movey * (float)model[10];

        glEnable(GL_FOG);

        if (sample)
            sample->handleRender();
        if (test)
            test->handleRender();
        
        glDisable(GL_FOG);
        
        // Render GUI
        glDisable(GL_DEPTH_TEST);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        gluOrtho2D(0, width, 0, height);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        
        mouseOverMenu = false;
        
        imguiBeginFrame(mx,my,mbut,mscroll);
        
        if (sample)
        {
            sample->handleRenderOverlay((double*)proj, (double*)model, (int*)view);
        }
        if (test)
        {
            if (test->handleRenderOverlay((double*)proj, (double*)model, (int*)view))
                mouseOverMenu = true;
        }

        // Help text.
        if (showMenu)
        {
            const char msg[] = "W/S/A/D: Move  RMB: Rotate   LMB+SHIFT: Place Start   LMB: Place End";
            imguiDrawText(width/2, height-20, IMGUI_ALIGN_CENTER, msg, imguiRGBA(255,255,255,128));
        }
        
        if (showMenu)
        {
            int propDiv = showDebugMode ? (int)(height*0.6f) : height;
            
            if (imguiBeginScrollArea("Properties",
                                     width-250-10, 10+height-propDiv, 250, propDiv-20, &propScroll))
                mouseOverMenu = true;

            if (imguiCheck("Show Log", showLog))
                showLog = !showLog;
            if (imguiCheck("Show Tools", showTools))
                showTools = !showTools;
            if (imguiCheck("Show Debug Mode", showDebugMode))
                showDebugMode = !showDebugMode;

            imguiSeparator();
            imguiLabel("Sample");
            if (imguiButton(sampleName))
            {
                if (showSample)
                {
                    showSample = false;
                }
                else
                {
                    showMaps = false;
                    showSample = true;
                    showLevels = false;
                    showTestCases = false;
                }
            }
            
            imguiSeparator();
            imguiLabel("Map");
            if (imguiButton(mapName, strncmp(sampleName, "Choose Sample...", 16)))
            {
                if (showMaps)
                {
                    showMaps = false;
                }
                else
                {
                    showMaps = true;
                    showSample = false;
                    showTestCases = false;
                    showLevels = false;
                    scanDirectory("Meshes", ".map", maps);
                }
            }

            imguiSeparator();
            imguiLabel("Tile");
            if (imguiButton(meshName, strncmp(mapName, "Choose Map...", 13)))
            {
                if (showLevels)
                {
                    showLevels = false;
                }
                else
                {
                    showMaps = false;
                    showSample = false;
                    showTestCases = false;
                    showLevels = true;
                    scanDirectory("Meshes", ".mesh", files);
                }
            }
            if (geom)
            {
                char text[64];
                snprintf(text, 64, "Verts: %.1fk  Tris: %.1fk",
                         geom->getMesh()->getVertCount()/1000.0f,
                         geom->getMesh()->getTriCount()/1000.0f);
                imguiValue(text);
            }
            imguiSeparator();
                    
            if (geom && sample)
            {
                sample->handleSettings();

                if (imguiButton("Build"))
                {
                    ctx.resetLog();
                    if (!sample->handleBuild())
                    {
                        showLog = true;
                        logScroll = 0;
                    }
                    ctx.dumpLog("Build log %s:", meshName);
                    
                    // Clear test.
                    delete test;
                    test = 0;
                }

                imguiSeparator();
            }
            
            imguiEndScrollArea();
            
            if (showDebugMode)
            {
                if (imguiBeginScrollArea("Debug Mode",
                                         width-250-10, 10,
                                         250, height-propDiv-10, &debugScroll))
                    mouseOverMenu = true;

                if (sample)
                    sample->handleDebugMode();

                imguiEndScrollArea();
            }
        }
        
        // Sample selection dialog.
        if (showSample)
        {
            static int levelScroll = 0;
            if (imguiBeginScrollArea("Choose Sample", width-10-250-10-200, height-10-250, 200, 250, &levelScroll))
                mouseOverMenu = true;

            Sample* newSample = 0;
            for (int i = 0; i < g_nsamples; ++i)
            {
                if (imguiItem(g_samples[i].name))
                {
                    newSample = g_samples[i].create();
                    if (newSample)
                        strcpy(sampleName, g_samples[i].name);
                }
            }
            if (newSample)
            {
                delete sample;
                sample = newSample;
                sample->setContext(&ctx);
                if (geom && sample)
                {
                    sample->handleMeshChanged(geom);
                }
                showSample = false;
            }

            if (geom || sample)
            {
                const float* bmin = 0;
                const float* bmax = 0;
                if (sample)
                {
                    bmin = sample->getBoundsMin();
                    bmax = sample->getBoundsMax();
                }
                else if (geom)
                {
                    bmin = geom->getMeshBoundsMin();
                    bmax = geom->getMeshBoundsMax();
                }
                // Reset camera and fog to match the mesh bounds.
                if (bmin && bmax)
                {
                    camr = sqrtf(rcSqr(bmax[0]-bmin[0]) +
                                 rcSqr(bmax[1]-bmin[1]) +
                                 rcSqr(bmax[2]-bmin[2])) / 2;
                    camx = (bmax[0] + bmin[0]) / 2 + camr;
                    camy = (bmax[1] + bmin[1]) / 2 + camr;
                    camz = (bmax[2] + bmin[2]) / 2 + camr;
                    camr *= 3;
                }
                rx = 45;
                ry = -45;
                glFogf(GL_FOG_START, camr*0.2f);
                glFogf(GL_FOG_END, camr*1.25f);
            }
            
            imguiEndScrollArea();
        }
        
        // map selection dialog
        if (showMaps)
        {
            static int scrolPos = 0;
            if (imguiBeginScrollArea("Choose Map", width-10-250-10-200, height-10-450, 200, 450, &scrolPos))
                mouseOverMenu = true;

            int selectedMap = -1;
            for (int i = 0; i < maps.size; ++i)
                if (imguiItem(maps.files[i]))
                    selectedMap = i;

            if (selectedMap != -1)
            {
                strncpy(mapName, maps.files[selectedMap], sizeof(mapName));
                mapName[sizeof(mapName)-1] = '\0';
                showMaps = false;

                delete geom;
                geom = NULL;

                if (sample)
                    sample->setMeshName(meshName);
            }
        }

        // Level selection dialog.
        if (showLevels)
        {
            static int levelScroll = 0;
            if (imguiBeginScrollArea("Choose Tile", width-10-250-10-200, height-10-450, 200, 450, &levelScroll))
                mouseOverMenu = true;
            
            int levelToLoad = -1;
            for (int i = 0; i < files.size; ++i)
            {
                if (!strncmp(mapName, files.files[i], 3))
                {
                    if (imguiItem(files.files[i]))
                        levelToLoad = i;
                }
            }
            
            if (levelToLoad != -1)
            {
                strncpy(meshName, files.files[levelToLoad], sizeof(meshName));
                meshName[sizeof(meshName)-1] = '\0';
                showLevels = false;
                
                delete geom;
                geom = 0;
                
                char path[256];
                strcpy(path, "Meshes/");
                strcat(path, meshName);
                
                geom = new InputGeom;
                if (!geom || !geom->loadMesh(&ctx, path))
                {
                    delete geom;
                    geom = 0;
                    
                    showLog = true;
                    logScroll = 0;
                    ctx.dumpLog("Geom load log %s:", meshName);
                }
                if (sample && geom)
                {
                    sample->handleMeshChanged(geom);
                    sample->setMeshName(meshName);
                }

                if (geom || sample)
                {
                    const float* bmin = 0;
                    const float* bmax = 0;
                    if (sample)
                    {
                        bmin = sample->getBoundsMin();
                        bmax = sample->getBoundsMax();
                    }
                    else if (geom)
                    {
                        bmin = geom->getMeshBoundsMin();
                        bmax = geom->getMeshBoundsMax();
                    }
                    // Reset camera and fog to match the mesh bounds.
                    if (bmin && bmax)
                    {
                        camr = sqrtf(rcSqr(bmax[0]-bmin[0]) +
                                     rcSqr(bmax[1]-bmin[1]) +
                                     rcSqr(bmax[2]-bmin[2])) / 2;
                        camx = (bmax[0] + bmin[0]) / 2 + camr;
                        camy = (bmax[1] + bmin[1]) / 2 + camr;
                        camz = (bmax[2] + bmin[2]) / 2 + camr;
                        camr *= 3;
                    }
                    rx = 45;
                    ry = -45;
                    glFogf(GL_FOG_START, camr*0.2f);
                    glFogf(GL_FOG_END, camr*1.25f);
                }
            }
            
            imguiEndScrollArea();
            
        }
        
        // Test cases
        if (showTestCases)
        {
            static int testScroll = 0;
            if (imguiBeginScrollArea("Choose Test To Run", width-10-250-10-200, height-10-450, 200, 450, &testScroll))
                mouseOverMenu = true;

            int testToLoad = -1;
            for (int i = 0; i < files.size; ++i)
            {
                if (imguiItem(files.files[i]))
                    testToLoad = i;
            }
            
            if (testToLoad != -1)
            {
                char path[256];
                strcpy(path, "Tests/");
                strcat(path, files.files[testToLoad]);
                test = new TestCase;
                if (test)
                {
                    // Load the test.
                    if (!test->load(path))
                    {
                        delete test;
                        test = 0;
                    }

                    // Create sample
                    Sample* newSample = 0;
                    for (int i = 0; i < g_nsamples; ++i)
                    {
                        if (strcmp(g_samples[i].name, test->getSampleName()) == 0)
                        {
                            newSample = g_samples[i].create();
                            if (newSample) strcpy(sampleName, g_samples[i].name);
                        }
                    }
                    if (newSample)
                    {
                        delete sample;
                        sample = newSample;
                        sample->setContext(&ctx);
                        showSample = false;
                    }

                    // Load geom.
                    strcpy(meshName, test->getGeomFileName());
                    meshName[sizeof(meshName)-1] = '\0';
                    
                    delete geom;
                    geom = 0;
                    
                    strcpy(path, "Meshes/");
                    strcat(path, meshName);
                    
                    geom = new InputGeom;
                    if (!geom || !geom->loadMesh(&ctx, path))
                    {
                        delete geom;
                        geom = 0;
                        
                        showLog = true;
                        logScroll = 0;
                        ctx.dumpLog("Geom load log %s:", meshName);
                    }
                    if (sample && geom)
                    {
                        sample->handleMeshChanged(geom);
                    }

                    ctx.resetLog();
                    if (sample && !sample->handleBuild())
                    {
                        ctx.dumpLog("Build log %s:", meshName);
                    }
                    
                    if (geom || sample)
                    {
                        const float* bmin = 0;
                        const float* bmax = 0;
                        if (sample)
                        {
                            bmin = sample->getBoundsMin();
                            bmax = sample->getBoundsMax();
                        }
                        else if (geom)
                        {
                            bmin = geom->getMeshBoundsMin();
                            bmax = geom->getMeshBoundsMax();
                        }
                        // Reset camera and fog to match the mesh bounds.
                        if (bmin && bmax)
                        {
                            camr = sqrtf(rcSqr(bmax[0]-bmin[0]) +
                                         rcSqr(bmax[1]-bmin[1]) +
                                         rcSqr(bmax[2]-bmin[2])) / 2;
                            camx = (bmax[0] + bmin[0]) / 2 + camr;
                            camy = (bmax[1] + bmin[1]) / 2 + camr;
                            camz = (bmax[2] + bmin[2]) / 2 + camr;
                            camr *= 3;
                        }
                        rx = 45;
                        ry = -45;
                        glFogf(GL_FOG_START, camr*0.2f);
                        glFogf(GL_FOG_END, camr*1.25f);
                    }
                    
                    // Do the tests.
                    if (sample)
                        test->doTests(sample->getNavMesh(), sample->getNavMeshQuery());
                }
            }                
                
            imguiEndScrollArea();
        }

        
        // Log
        if (showLog && showMenu)
        {
            if (imguiBeginScrollArea("Log", 10, 10, width - 300, 200, &logScroll))
                mouseOverMenu = true;
            for (int i = 0; i < ctx.getLogCount(); ++i)
                imguiLabel(ctx.getLogText(i));
            imguiEndScrollArea();
        }
        
        // Tools
        if (!showTestCases && showTools && showMenu && geom && sample)
        {
            if (imguiBeginScrollArea("Tools", 10, height - 10 - 350, 250, 350, &toolsScroll))
                mouseOverMenu = true;

            sample->handleTools();
            
            imguiEndScrollArea();
        }
        
        slideShow.updateAndDraw(dt, (float)width, (float)height);
        
        // Marker
        if (mposSet && gluProject((GLdouble)mpos[0], (GLdouble)mpos[1], (GLdouble)mpos[2],
                                  model, proj, view, &x, &y, &z))
        {
            // Draw marker circle
            glLineWidth(5.0f);
            glColor4ub(240,220,0,196);
            glBegin(GL_LINE_LOOP);
            const float r = 25.0f;
            for (int i = 0; i < 20; ++i)
            {
                const float a = (float)i / 20.0f * RC_PI*2;
                const float fx = (float)x + cosf(a)*r;
                const float fy = (float)y + sinf(a)*r;
                glVertex2f(fx,fy);
            }
            glEnd();
            glLineWidth(1.0f);
        }
        
        imguiEndFrame();
        imguiRenderGLDraw();        
        
        glEnable(GL_DEPTH_TEST);
        SDL_GL_SwapBuffers();
    }
    
    imguiRenderGLDestroy();
    
    SDL_Quit();
    
    delete sample;
    delete geom;
    
    return 0;
}
Beispiel #7
0
void ditto_render()
{
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  
  glTranslatef(0.0f, 0.0f, -20.0f);
  
  GLfloat ambientLight[] = {0.3f, 0.3f, 0.3f, 1.0f};
  glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientLight);
  
  GLfloat lightColor[] = {0.7f, 0.7f, 0.7f, 1.0f};
  GLfloat lightPos[] = {-2 * BOX_SIZE, BOX_SIZE, 4 * BOX_SIZE, 1.0f};
  glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColor);
  glLightfv(GL_LIGHT0, GL_POSITION, lightPos);
  
  glRotatef(-angle, 1.0f, 1.0f, 1.0f);
  
  glBegin(GL_QUADS);
    //Top face
    glColor3f(1.0f, 1.0f, 0.0f);
    glNormal3f(0.0, 1.0f, 0.0f);
    glVertex3f(-BOX_SIZE / 2, BOX_SIZE / 2, -BOX_SIZE / 2);
    glVertex3f(-BOX_SIZE / 2, BOX_SIZE / 2, BOX_SIZE / 2);
    glVertex3f(BOX_SIZE / 2, BOX_SIZE / 2, BOX_SIZE / 2);
    glVertex3f(BOX_SIZE / 2, BOX_SIZE / 2, -BOX_SIZE / 2);
    
    //Bottom face
    glColor3f(1.0f, 0.0f, 1.0f);
    glNormal3f(0.0, -1.0f, 0.0f);
    glVertex3f(-BOX_SIZE / 2, -BOX_SIZE / 2, -BOX_SIZE / 2);
    glVertex3f(BOX_SIZE / 2, -BOX_SIZE / 2, -BOX_SIZE / 2);
    glVertex3f(BOX_SIZE / 2, -BOX_SIZE / 2, BOX_SIZE / 2);
    glVertex3f(-BOX_SIZE / 2, -BOX_SIZE / 2, BOX_SIZE / 2);
    
    //Left face
    glNormal3f(-1.0, 0.0f, 0.0f);
    glColor3f(0.0f, 1.0f, 1.0f);
    glVertex3f(-BOX_SIZE / 2, -BOX_SIZE / 2, -BOX_SIZE / 2);
    glVertex3f(-BOX_SIZE / 2, -BOX_SIZE / 2, BOX_SIZE / 2);
    glColor3f(0.0f, 0.0f, 1.0f);
    glVertex3f(-BOX_SIZE / 2, BOX_SIZE / 2, BOX_SIZE / 2);
    glVertex3f(-BOX_SIZE / 2, BOX_SIZE / 2, -BOX_SIZE / 2);
    
    //Right face
    glNormal3f(1.0, 0.0f, 0.0f);
    glColor3f(1.0f, 0.0f, 0.0f);
    glVertex3f(BOX_SIZE / 2, -BOX_SIZE / 2, -BOX_SIZE / 2);
    glVertex3f(BOX_SIZE / 2, BOX_SIZE / 2, -BOX_SIZE / 2);
    glColor3f(0.0f, 1.0f, 0.0f);
    glVertex3f(BOX_SIZE / 2, BOX_SIZE / 2, BOX_SIZE / 2);
    glVertex3f(BOX_SIZE / 2, -BOX_SIZE / 2, BOX_SIZE / 2);
  glEnd();
  
  glEnable(GL_TEXTURE_2D);
  glBindTexture(GL_TEXTURE_2D, texture);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glColor3f(1.0f, 1.0f, 1.0f);
  glBegin(GL_QUADS);
    //Front face
    glNormal3f(0.0, 0.0f, 1.0f);
    glTexCoord2f(1.0f, 1.0f);
    glVertex3f(-BOX_SIZE / 2, -BOX_SIZE / 2, BOX_SIZE / 2);
    glTexCoord2f(0.0f, 1.0f);
    glVertex3f(BOX_SIZE / 2, -BOX_SIZE / 2, BOX_SIZE / 2);
    glTexCoord2f(0.0f, 0.0f);
    glVertex3f(BOX_SIZE / 2, BOX_SIZE / 2, BOX_SIZE / 2);
    glTexCoord2f(1.0f, 0.0f);
    glVertex3f(-BOX_SIZE / 2, BOX_SIZE / 2, BOX_SIZE / 2);
    
    //Back face
    glNormal3f(0.0, 0.0f, -1.0f);
    glTexCoord2f(1.0f, 1.0f);
    glVertex3f(-BOX_SIZE / 2, -BOX_SIZE / 2, -BOX_SIZE / 2);
    glTexCoord2f(0.0f, 1.0f);
    glVertex3f(-BOX_SIZE / 2, BOX_SIZE / 2, -BOX_SIZE / 2);
    glTexCoord2f(0.0f, 0.0f);
    glVertex3f(BOX_SIZE / 2, BOX_SIZE / 2, -BOX_SIZE / 2);
    glTexCoord2f(1.0f, 0.0f);
    glVertex3f(BOX_SIZE / 2, -BOX_SIZE / 2, -BOX_SIZE / 2);
  glEnd();
  glDisable(GL_TEXTURE_2D);
  
  SDL_GL_SwapBuffers();
}
Beispiel #8
0
void gemsdlwindow :: swapBuffers(void) {
  if(makeCurrent()) // FIXME: is this needed?
    SDL_GL_SwapBuffers();
}
void LoadingBar::Draw(float val)
{
	// percent complete bar only draws in 2d mode
	prj->set_orthographic_projection();

	// Draw the splash screen if available
	if (splash) {
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		glEnable(GL_TEXTURE_2D);
		glColor3f(1, 1, 1);
		glDisable(GL_CULL_FACE);
		glBindTexture(GL_TEXTURE_2D, splash->getID());

		glBegin(GL_QUADS);
		glTexCoord2i(0, 0);		// Bottom Left
		glVertex3f(splashx, splashy, 0.0f);
		glTexCoord2i(1, 0);		// Bottom Right
		glVertex3f(splashx + width, splashy, 0.0f);
		glTexCoord2i(1, 1);		// Top Right
		glVertex3f(splashx + width, splashy + height, 0.0f);
		glTexCoord2i(0, 1);		// Top Left
		glVertex3f(splashx, splashy + height, 0.0f);
		glEnd();
	}
	glDisable(GL_BLEND);
	glDisable(GL_TEXTURE_2D);

	// black out background of text for redraws (so can keep sky unaltered)
	glColor3f(0, 0, 0);
	glBegin(GL_QUAD_STRIP);
	glTexCoord2i(1, 0);		// Bottom Right
	glVertex3f(splashx + width, bary-70, 0.0f);
	glTexCoord2i(0, 0);		// Bottom Left
	glVertex3f(splashx, bary-70, 0.0f);
	glTexCoord2i(1, 1);		// Top Right
	glVertex3f(splashx + width, bary-5, 0.0f);
	glTexCoord2i(0, 1);		// Top Left
	glVertex3f(splashx, bary-5, 0.0f);
	glEnd();
	glColor3f(0.8, 0.8, 1);
	glBegin(GL_QUAD_STRIP);
	glTexCoord2i(1, 0);		// Bottom Right
	glVertex3f(barx + barwidth, bary + barheight, 0.0f);
	glTexCoord2i(0, 0);		// Bottom Left
	glVertex3f(barx, bary + barheight, 0.0f);
	glTexCoord2i(1, 1);		// Top Right
	glVertex3f(barx + barwidth, bary, 0.0f);
	glTexCoord2i(0, 1);		// Top Left
	glVertex3f(barx, bary, 0.0f);
	glEnd();
	glColor3f(0.4f, 0.4f, 0.6f);
	glBegin(GL_QUAD_STRIP);
	glTexCoord2i(1, 0);		// Bottom Right
	glVertex3f(-1 + barx + barwidth * val, bary + barheight - 1, 0.0f);
	glTexCoord2i(0, 0);		// Bottom Left
	glVertex3f(1 + barx, bary + barheight - 1, 0.0f);
	glTexCoord2i(1, 1);		// Top Right
	glVertex3f(-1 + barx + barwidth * val, bary + 1, 0.0f);
	glTexCoord2i(0, 1);		// Top Left
	glVertex3f(1 + barx, bary + 1, 0.0f);
	glEnd();

	glColor3f(1, 1, 1);
	glEnable(GL_TEXTURE_2D);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Normal transparency mode

	if(barfont) {
		barfont->print(barx, bary-15, message);
		// LEGAL NOTICES -- THE DISPLAY OF THESE AT STARTUP MAY NOT BE REMOVED as per GPL section 5
		barfont->print(barx-20, bary-40, "<span color='#666699'>Nightshade is free, open source software with a GPLv3 license.</span>");
		barfont->print(barx-20, bary-55, "<span color='#666699'>Nightshade is a registered trademark of Digitalis Education Solutions, Inc.</span>");
	}

	if(extraTextFont) {
		extraTextFont->print(splashx + extraTextPos[0], splashy + extraTextPos[1], extraText);
		extraTextFont->print(splashx + extraTextPos[0], splashy + extraTextPos[1] - 20, EDITION); 
		extraTextFont->print(splashx + extraTextPos[0], splashy + extraTextPos[1] - 40, "Edition"); 
	}
	SDL_GL_SwapBuffers();	// And swap the buffers

	prj->reset_perspective_projection();
}
Beispiel #10
0
int main(int argc, char *argv[])
{
    SDL_Surface *screen;

    // Slightly different SDL initialization
    if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) {
        printf("Unable to initialize SDL: %s\n", SDL_GetError());
        return 1;
    }

    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); // *new*

    screen = SDL_SetVideoMode( 640, 480, 16, SDL_OPENGL ); // *changed*
    if ( !screen ) {
        printf("Unable to set video mode: %s\n", SDL_GetError());
        return 1;
    }

    // Check extensions

    const char *exts = (const char *)glGetString(GL_EXTENSIONS);
    assert(hasext(exts, "GL_ARB_texture_compression"));
    assert(hasext(exts, "GL_EXT_texture_compression_s3tc"));

    // Set the OpenGL state after creating the context with SDL_SetVideoMode

    glClearColor( 0, 0, 0, 0 );

    glEnable( GL_TEXTURE_2D ); // Needed when we're using the fixed-function pipeline.

    glViewport( 0, 0, 640, 480 );

    glMatrixMode( GL_PROJECTION );
    GLfloat matrixData[] = { 2.0/640,        0,  0,  0,
                                   0, -2.0/480,  0,  0,
                                   0,        0, -1,  0,
                                  -1,        1,  0,  1 };
    glLoadMatrixf(matrixData); // test loadmatrix

    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();


    // Load the OpenGL textures

    GLuint texture;

    {
      const int DDS_SIZE = 65664;
      FILE *dds = fopen("ship.dds", "rb");
      assert(dds);
      char *ddsdata = (char*)malloc(DDS_SIZE);
      assert(fread(ddsdata, 1, DDS_SIZE, dds) == DDS_SIZE);
      fclose(dds);

      glGenTextures( 1, &texture );
      glBindTexture( GL_TEXTURE_2D, texture );

      assert(!glGetError());
      glCompressedTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, 256, 256, 0, DDS_SIZE-128, ddsdata+128);
      assert(!glGetError());

      glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
      glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
    }

    // second texture

    GLuint texture2;

    {
      const int DDS_SIZE = 32896;
      FILE *dds = fopen("bloom.dds", "rb");
      assert(dds);
      char *ddsdata = (char*)malloc(DDS_SIZE);
      assert(fread(ddsdata, 1, DDS_SIZE, dds) == DDS_SIZE);
      fclose(dds);

      glGenTextures( 1, &texture2 );
      glBindTexture( GL_TEXTURE_2D, texture2 );

      assert(!glGetError());
      glCompressedTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, 256, 256, 0, DDS_SIZE-128, ddsdata+128);
      assert(!glGetError());

      glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
      glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
    }

    // third, a non-square texture with mipmaps

    GLuint texture3;

    {
      const int DDS_SIZE = 43920;
      FILE *dds = fopen("water.dds", "rb");
      assert(dds);
      char *ddsdata = (char*)malloc(DDS_SIZE);
      assert(fread(ddsdata, 1, DDS_SIZE, dds) == DDS_SIZE);
      fclose(dds);

      glGenTextures( 1, &texture3 );
      glBindTexture( GL_TEXTURE_2D, texture3 );

      assert(!glGetError());
      glCompressedTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, 512, 64, 0, 512*64, ddsdata+128);
      assert(!glGetError());

      glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
      glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
    }

    // Prepare and Render

    // Clear the screen before drawing
    glClear( GL_COLOR_BUFFER_BIT );

    // Bind the texture to which subsequent calls refer to
    glBindTexture( GL_TEXTURE_2D, texture );

    // Use clientside vertex pointers to render two items
    GLfloat vertexData[] = { 0, 0, 10, 10, // texture2, position2
                             1, 0, 300, 10,
                             1, 1, 300, 128,
                             0, 1, 10, 128,
                             0, 0.5, 410, 10,
                             1, 0.5, 600, 10,
                             1, 1, 630, 200,
                             0.5, 1, 310, 250 };

    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    glTexCoordPointer(2, GL_FLOAT, 4*4, &vertexData[0]);
    glEnableClientState(GL_VERTEX_ARRAY);
    glVertexPointer(2, GL_FLOAT, 4*4, &vertexData[2]);

    glDrawArrays(GL_QUADS, 0, 4);

    glBindTexture( GL_TEXTURE_2D, texture3 );
    glDrawArrays(GL_QUADS, 4, 4);

    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    glDisableClientState(GL_VERTEX_ARRAY);

    // Render the last item using oldschool glBegin etc
    glBindTexture( GL_TEXTURE_2D, texture2 );
    glBegin( GL_TRIANGLE_STRIP );
        glTexCoord2i( 0, 0 ); glVertex3f( 100, 300, 0 );
        glTexCoord2i( 1, 0 ); glVertex3f( 300, 300, 0 );
        glTexCoord2i( 1, 1 ); glVertex3f( 300, 400, 0 );
        glTexCoord2i( 0, 1 ); glVertex3f( 500, 410, 0 );
    glEnd();

    SDL_GL_SwapBuffers();

#if !EMSCRIPTEN
    // Wait for 3 seconds to give us a chance to see the image
    SDL_Delay(1500);
#endif

    // Now we can delete the OpenGL texture and close down SDL
    glDeleteTextures( 1, &texture );

    SDL_Quit();

    return 0;
}
Beispiel #11
0
void display() {
	int i, wm;
	float size = 5;

	if (!can_render()) {
		return;
	}

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	if (render_mode == IR) {
		/* draw the IR stuff */

		glDisable(GL_LIGHTING);

		glBegin(GL_TRIANGLES);
		/* green center */
		glColor3f(0.0, 1.0, 0.0);
		DRAW_TRIANGLE(width / 2, height / 2, 0, size);
		glEnd();

		for (wm = 0; wm < MAX_WIIMOTES; ++wm) {
			glBegin(GL_TRIANGLES);
			/* red ir */
			glColor3f(1.0, 0.0, 0.0);
			for (i = 0; i < 4; ++i) {
				if (wiimotes[wm]->ir.dot[i].visible) {
					DRAW_TRIANGLE(wiimotes[wm]->ir.dot[i].rx, wiimotes[wm]->ir.dot[i].ry, 0, size);
				}
			}

			/* yellow corrected ir */
			glColor3f(1.0, 1.0, 0.0);
			for (i = 0; i < 4; ++i) {
				if (wiimotes[wm]->ir.dot[i].visible) {
					DRAW_TRIANGLE(wiimotes[wm]->ir.dot[i].x, wiimotes[wm]->ir.dot[i].y, 0, size);
				}
			}

			/* blue cursor */
			glColor3f(0.0, 0.0, 1.0);
			DRAW_TRIANGLE(wiimotes[wm]->ir.x, wiimotes[wm]->ir.y - size, 0, size);
			glEnd();
		}
	} else {
		/* draw the teapot */
		gluLookAt(0.0, 0.0, -5.0,
		          0.0, 0.0, 0.0,
		          0.0, 1.0, 0.0);

		glEnable(GL_LIGHTING);
		glEnable(GL_LIGHT0);
		update_light(GL_LIGHT0, &light);
		set_material(&red_plastic);

		glRotatef(wiimotes[0]->orient.roll, 0.0f, 0.0f, 1.0f);
		glRotatef(wiimotes[0]->orient.pitch, 1.0f, 0.0f, 0.0f);


		glutSolidTeapot(1);
	}

	SDL_GL_SwapBuffers();
}
Beispiel #12
0
/*
 * r_drawFrame
 * Perform any drawing and setup necessary to produce a single frame.
 */
static void r_drawFrame()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	//Orient and position the camera
	r_setupModelview();

	//Draw sky?
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glPushMatrix();
	glLoadIdentity();
	r_setupModelviewforSky();
	renderer_model_drawASE(0);
	glPopMatrix();


	glClear(GL_DEPTH_BUFFER_BIT);

	//Draw fighter. Needs to stay with the camera.
	//Doesn't rotate. Only stays in the same position relative to camera.
	glPushMatrix();
	glLoadIdentity();
	renderer_model_drawASE(1);
	glPopMatrix();

	//Texture stuff past this point.
	glColor3f(1.0, 1.0, 1.0);


	glBindTexture(GL_TEXTURE_2D, face1);
	glBegin(GL_QUADS);
		//Set up appropriate texture for the forward face.

		//I've been visualizing this the wrong way. Each four is considered a square.
		//Face 1
		glTexCoord2f(0.0, 0.0);
			glVertex3f(-0.5, -0.5, -8.0);
		glTexCoord2f(1.0, 0.0);
			glVertex3f( 0.5, -0.5, -8.0);
		glTexCoord2f(1.0, 1.0);
			glVertex3f( 0.5,  0.5, -8.0);
		glTexCoord2f(0.0, 1.0);
			glVertex3f(-0.5,  0.5, -8.0);
	glEnd();

		//Face 2
		glBindTexture(GL_TEXTURE_2D, face4);
	glBegin(GL_QUADS);
		glTexCoord2f(0.0, 0.0);
			glVertex3f(-0.5, -0.5, -9.0);
		glTexCoord2f(1.0, 0.0);
			glVertex3f(-0.5, -0.5, -8.0);
		glTexCoord2f(1.0, 1.0);
			glVertex3f(-0.5, 0.5, -8.0);
		glTexCoord2f(0.0, 1.0);
			glVertex3f(-0.5, 0.5, -9.0);
	glEnd();

		//Face 3
		glBindTexture(GL_TEXTURE_2D, face3);
		glBegin(GL_QUADS);
		glTexCoord2f(0.0, 0.0);
			glVertex3f(0.5, -0.5, -8.0);
		glTexCoord2f(1.0, 0.0);
			glVertex3f(0.5, -0.5, -9.0);
		glTexCoord2f(1.0, 1.0);
			glVertex3f(0.5, 0.5, -9.0);
		glTexCoord2f(0.0, 1.0);
			glVertex3f(0.5, 0.5, -8.0);
		glEnd();

		//Face 4
		glBindTexture(GL_TEXTURE_2D, face6);
		glBegin(GL_QUADS);
		glTexCoord2f(0.0, 0.0);
			glVertex3f(0.5, -0.5, -9.0);
		glTexCoord2f(1.0, 0.0);
			glVertex3f(-0.5, -0.5, -9.0);
		glTexCoord2f(1.0, 1.0);
			glVertex3f(-0.5, 0.5, -9.0);
		glTexCoord2f(0.0, 1.0);
			glVertex3f(0.5, 0.5, -9.0);
			glEnd();

		//Face 5
		glBindTexture(GL_TEXTURE_2D, face5);
		glBegin(GL_QUADS);
		glTexCoord2f(0.0, 0.0);
			glVertex3f(-0.5, 0.5, -8.0);
		glTexCoord2f(1.0, 0.0);
			glVertex3f(0.5, 0.5, -8.0);
		glTexCoord2f(1.0, 1.0);
			glVertex3f(0.5, 0.5, -9.0);
		glTexCoord2f(0.0, 1.0);
			glVertex3f(-0.5, 0.5, -9.0);
		glEnd();

		//Face 6
		glBindTexture(GL_TEXTURE_2D, face2);
		glBegin(GL_QUADS);
		glTexCoord2f(0.0, 0.0);
			glVertex3f(0.5, -0.5, -8.0);
		glTexCoord2f(1.0, 0.0);
			glVertex3f(-0.5, -0.5, -8.0);
		glTexCoord2f(1.0, 1.0);
			glVertex3f(-0.5, -0.5, -9.0);
		glTexCoord2f(0.0, 1.0);
			glVertex3f(0.5, -0.5, -9.0);
	glEnd();

	SDL_GL_SwapBuffers();
}
Beispiel #13
0
void Graphics::SwapFrameBuffer()
{
    // Swap OpenGL framebuffer
    SDL_GL_SwapBuffers();
}
Beispiel #14
0
void gl_drawwin()
{
	int i;

	NGNoTransp = 0;		// Set this value to 1 within the appropriate
				// video mode if you want to add a custom
				// transparency routine or hardware
				// transparency.  This only works if
				// the value of newengen is equal to 1.
				// (see ProcessTransparencies in newgfx16.asm
				//  for ZSNES' current transparency code)
	UpdateVFrame();
	if (curblank != 0)
		return;

	if (BilinearFilter)
	{
		glfilters = GL_LINEAR;
		if (GUIOn2 && !FilteredGUI)
			glfilters = GL_NEAREST;
	}
	else
	{
		glfilters = GL_NEAREST;
	}

	if (En2xSaI && SurfaceX != 256)
	{
		/* We have to use copy640x480x16bwin for 2xSaI */
		AddEndBytes = 0;
		NumBytesPerLine = 1024;
		WinVidMemStart = (void *) glvidbuffer;
		copy640x480x16bwin();

		/* Display 4 256x256 quads for the 512x448 buffer */
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, glfilters);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, glfilters);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

		/* Upper left quad */
		glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
		glPixelStorei(GL_UNPACK_ROW_LENGTH, 512);
		glTexImage2D(GL_TEXTURE_2D, 0, 3, 256, 256, 0,
			     GL_RGB, GL_UNSIGNED_SHORT_5_6_5, glvidbuffer);

		glBegin(GL_QUADS);
			glTexCoord2f(0.0f, 0.0f);
			glVertex3f(-1.0f, 1.0f, -1.0f);
			glTexCoord2f(1.0f, 0.0f);
			glVertex3f(0.0f, 1.0f, -1.0f);
			glTexCoord2f(1.0f, (224.0 / 256.0));
			glVertex3f(0.0f, 0.0f, -1.0f);
			glTexCoord2f(0.0f, (224.0 / 256.0));
			glVertex3f(-1.0f, 0.0f, -1.0f);
		glEnd();

		/* Upper right quad */
		glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
		glPixelStorei(GL_UNPACK_ROW_LENGTH, 512);
		glTexImage2D(GL_TEXTURE_2D, 0, 3, 256, 256, 0,
			     GL_RGB, GL_UNSIGNED_SHORT_5_6_5,
			     glvidbuffer + 256);

		glBegin(GL_QUADS);
			glTexCoord2f(0.0f, 0.0f);
			glVertex3f(0.0f, 1.0f, -1.0f);
			glTexCoord2f(1.0f, 0.0f);
			glVertex3f(1.0f, 1.0f, -1.0f);
			glTexCoord2f(1.0f, (224.0 / 256.0));
			glVertex3f(1.0f, 0.0f, -1.0f);
			glTexCoord2f(0.0f, (224.0 / 256.0));
			glVertex3f(0.0f, 0.0f, -1.0f);
		glEnd();

		/* Lower left quad */
		glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
		glPixelStorei(GL_UNPACK_ROW_LENGTH, 512);
		glTexImage2D(GL_TEXTURE_2D, 0, 3, 256, 256, 0,
			     GL_RGB, GL_UNSIGNED_SHORT_5_6_5,
			     glvidbuffer + 512 * 224);

		glBegin(GL_QUADS);
			glTexCoord2f(0.0f, 0.0f);
			glVertex3f(-1.0f, 0.0f, -1.0f);
			glTexCoord2f(1.0f, 0.0f);
			glVertex3f(0.0f, 0.0f, -1.0f);
			glTexCoord2f(1.0f, (224.0 / 256.0));
			glVertex3f(0.0f, -1.0f, -1.0f);
			glTexCoord2f(0.0f, (224.0 / 256.0));
			glVertex3f(-1.0f, -1.0f, -1.0f);
		glEnd();

		/* Lower right quad */
		glTexImage2D(GL_TEXTURE_2D, 0, 3, 256, 256, 0,
			     GL_RGB, GL_UNSIGNED_SHORT_5_6_5,
			     glvidbuffer + 512 * 224 + 256);

		glBegin(GL_QUADS);
			glTexCoord2f(0.0f, 0.0f);
			glVertex3f(0.0f, 0.0f, -1.0f);
			glTexCoord2f(1.0f, 0.0f);
			glVertex3f(1.0f, 0.0f, -1.0f);
			glTexCoord2f(1.0f, (224.0 / 256.0));
			glVertex3f(1.0f, -1.0f, -1.0f);
			glTexCoord2f(0.0f, (224.0 / 256.0));
			glVertex3f(0.0f, -1.0f, -1.0f);
		glEnd();
	}
	else
	{
		/*
		 * This code splits the hires/lores portions up, and draws
		 * them with gl_drawspan
		 */
		int lasthires, lasthires_line = 0;

		gltexture256 = gltexture512 = 0;

		lasthires = SpecialLine[1];
		for (i = 1; i < 222; i++)
		{
			if (SpecialLine[i + 1])
			{
				if (lasthires)
					continue;
				gl_drawspan(lasthires, lasthires_line, i);

				lasthires = SpecialLine[i + 1];
				lasthires_line = i;
			}
			else
			{
				if (!lasthires)
					continue;
				gl_drawspan(lasthires, lasthires_line, i);

				lasthires = SpecialLine[i + 1];
				lasthires_line = i;
			}
		}
		gl_drawspan(lasthires, lasthires_line, i);

		/*
		 * This is here rather than right outside this if because the
		 * GUI doesn't allow scanlines to be selected while filters are
		 * on.. There is no technical reason they can't be on while
		 * filters are on, however.  Feel free to change the GUI, and
		 * move this outside the if (En2xSaI) {}, if you do.
		 */
		if (scanlines)
		{
			glDisable(GL_TEXTURE_2D);
			glEnable(GL_BLEND);

			glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
			glBindTexture(GL_TEXTURE_1D, gltextures[3]);
			glColor4f(1.0f, 1.0f, 1.0f,
				  scanlines == 1 ? 1.0f : (scanlines ==
							   2 ? 0.25f : 0.50f));
			for (i = 0; i < SurfaceY; i += 256)
			{
				glBegin(GL_QUADS);
				glTexCoord1f(0.0f);
				glVertex3f(-1.0f, (SurfaceY - i * 2.0) / SurfaceY, -1.0f);
				glTexCoord1f(0.0f);
				glVertex3f(1.0f, (SurfaceY - i * 2.0) / SurfaceY, -1.0f);
				glTexCoord1f(1.0f);
				glVertex3f(1.0f, (SurfaceY - (i + 256) * 2.0) / SurfaceY, -1.0f);
				glTexCoord1f(1.0f);
				glVertex3f(-1.0f, (SurfaceY - (i + 256) * 2.0) / SurfaceY, -1.0f);
				glEnd();
			}

			glDisable(GL_BLEND);
			glEnable(GL_TEXTURE_2D);
		}
	}
	SDL_GL_SwapBuffers();
}
Beispiel #15
0
bool MenuScreen::display_menu(SDL_Surface *screen,SELECTION &selection) {
	Uint32 ticks=SDL_GetTicks();
	Uint32 frame_count=0;

	//logo sprites
	const Sprite *logo_free=spr_coll->get_sprite("logo_free");
	const Sprite *logo_siege=spr_coll->get_sprite("logo_siege");
	//~ const Sprite *logo_sword=spr_coll->get_sprite("logo_sword");
	//background sprites
	const Sprite *back_hill=spr_coll->get_sprite("title_foreground");
	const Sprite *back_castle=spr_coll->get_sprite("title_castle");
	const Sprite *back_sky=spr_coll->get_sprite("title_sky");

	SDL_Event event;
	float shift=1.0;
	while (true) {
		Menu *current_menu=menus.top();
		
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		//fill_rect_opengl(0,0,SCREEN_W,SCREEN_H,1,1,0,1);
		back_sky->draw(0,0);

		back_castle->draw(0,CASTLE_BIAS+CASTLE_SHIFT*shift);
		back_hill->draw(0,HILL_BIAS+HILL_SHIFT*shift);
		shift-=D_SHIFT;
		if (shift<0) shift=0;

		//draw_fadein(logo_sword,(SCREEN_W-logo_sword->w)/2,MENUSCREEN_BASE_Y-logo_sword->h/2-4,frame_count,MENUSCREEN_SWORD_FRAME_COUNT,30,4);
		draw_fadein(logo_free,MENUSCREEN_BASE_X,MENUSCREEN_BASE_Y,frame_count,MENUSCREEN_FREE_FRAME_COUNT,MENUSCREEN_DELAY);
		draw_fadein(logo_siege,SCREEN_W-logo_siege->w-MENUSCREEN_BASE_X,MENUSCREEN_BASE_Y,frame_count,MENUSCREEN_SIEGE_FRAME_COUNT,MENUSCREEN_DELAY);
		current_menu->draw();
		SDL_GL_SwapBuffers();
		SDL_Flip(screen);

		while (SDL_PollEvent(&event)) {
			switch (event.type) {
			case SDL_KEYDOWN:
				switch (event.key.keysym.sym) {
				case SDLK_ESCAPE:
					if (!menus.empty()) menus.pop();
					if (menus.empty()) {
						selection=QUIT;
						return true;
					}
					break;
				case SDLK_RETURN:
				case SDLK_SPACE:
					if (current_menu==main_menu) {
						switch (current_menu->get_selected()->n) {
						case 0://2 players versus
							selection=TWO_PLAYERS;
							return false;
							break;
						case 1://training mode
							selection=TRAINING;
							return false;
							break;
						case 2://combinaisons
							selection=COMBINAISONS;
							return false;
							break;
						case 3://options
							menus.push(option_menu);
							break;
						case 4://quit
							selection=QUIT;
							return true;
							break;
						default:
							break;
						}
					} else if (current_menu==option_menu) {
						switch (current_menu->get_selected()->n) {
                        case 0://ai level
                            switch (ai_level) {
                              case EASY:
                                ai_level=NORMAL;
								current_menu->get_selected()->title="AI Level: Knight";
                                break;
                              case NORMAL:
                                ai_level=HARD;
								current_menu->get_selected()->title="AI Level: Galaad the Righteous";
                                break;
                              case HARD:
                                ai_level=EXTREME;
								current_menu->get_selected()->title="AI Level: Morgoth the Cruel";
                                break;
                              case EXTREME:
                                ai_level=EASY;
								current_menu->get_selected()->title="AI Level: Farmer";
                                break; }
                            break;
						case 1://keys
							menus.push(key_menu);
							break;
						case 2://Sound
							if (!Options::soundOn())
							{
								Mix_ResumeMusic();
								Options::setSound(true);
								current_menu->get_selected()->title="Sound: on";
							}
							else
							{
								Mix_PauseMusic();
								Options::setSound(false);
								current_menu->get_selected()->title="Sound: off";
							}
							break;
						case 4://return
							menus.pop();
							break;
						default:
							break;
						}
					} else if (current_menu==key_menu) {
					}
					break;
				case SDLK_UP:
					current_menu->previous();
					break;
				case SDLK_DOWN:
					current_menu->next();
					break;
				default:
					break;
				}
				break;
			case SDL_QUIT:			
				return true;
				break;
			default:
				break;
			}
		}

		while (ticks>(SDL_GetTicks()-1000/FPS)) SDL_Delay(3);
		ticks=SDL_GetTicks();
		frame_count++;
	}

	return true;
}
Beispiel #16
0
int main(int argc, char *argv[])
{
	//Essas duas funções servem pra criar a nossa janela. A primeira inicializa
	//a SDL, enquanto que a segunda cria de fato a janela. Os parâmetros para a
	//segunda função são: largura, altura, bpp, modo.
	//	* largura, altura: as dimensões da janela que queremos criar
	//	* bpp: bits per pixel, a "resolução de cores" da janela. O valor 32
	//	significa que queremos uma janela RGBA com 8 bits pra cada componente
	//	* modo: como a janela deve ser criada. O valor SDL_OPENGL indica que a
	//	janela deve ser criada com suporte a OpenGL
	SDL_Init(SDL_INIT_EVERYTHING);
	SDL_Surface *tela = SDL_SetVideoMode(300, 600, 32, SDL_OPENGL);

	//Ah, o loop principal. Jogue "false" em "rodando" e o programa para
	bool rodando = true;
	while (rodando)
	{
		//A primeira coisa a se fazer todo frame é verificar quais foram os
		//eventos gerados pelo sistema operacional no frame anterior. Por
		//"evento", entende-se:
		//	* Tecla pressionada/solta
		//	* Botão do mouse pressionado/solto
		//	* Mouse movimentado
		//	* Ícone "X" da janela clicado
		//	* Janela redimensionada
		//	* Outros eventos do sistema operacional que não nos interessam agora
		SDL_Event e;
		//A função SDL_PollEvent pega o primeiro evento não processado até
		//agora (são armazenados em uma fila). Ela retorna 0 quando não há mais
		//eventos pra serem processados e alguma coisa diferente de zero quando
		//há algo ainda pendente. Isso é usado pra tratar todos os eventos
		//_antes_ de fazer qualquer outra coisa no programa
		while (SDL_PollEvent(&e))
		{
			//Um evento bastante comum: tecla pressionada. Os códigos das teclas
			//como SDLK_ESCAPE, SDLK_UP etc. estão no arquivo SDL/SDL_keysym.h
			if (e.type == SDL_KEYDOWN)
				if ((e.key.keysym.sym == SDLK_ESCAPE) or (e.key.keysym.sym == SDLK_e))
					rodando = false;
			//Esse é o evento gerado quando o usuário clicou no "x" da janela.
			//Só clicar não faz nada, o programa é quem tem que decidir o que
			//fazer quando isso acontece. Aqui, só fechamos o programa direto
			if (e.type == SDL_QUIT)
				rodando = false;
		}

		//Esses comandos servem pra limpar a tela. O primeiro serve pra
		//especificar a cor que é pra ser usada pra limpar a tela, e não
		//precisaria ser chamada toda vez, pois ela seta a cor pra qual você
		//quer até que essa função seja chamada de novo. A segunda limpa de fato
		//a tela. O argumento indica o que deve ser limpo. Nesse caso, só
		//estamos limpando o "color buffer", mas há outros que usaremos em
		//outros projetos
		glClearColor(1,1,0,0);
		glClear(GL_COLOR_BUFFER_BIT);
		//Isso aqui é pra mostrar o buffer na tela. Até agora, todos os comandos
		//de desenhar alguma coisa foram aplicados em um buffer "escondido", pra
		//que não apareça na tela uma imagem pela metade. Essa função faz com
		//que o buffer que estava escondido seja mostrado e, a partir de agora,
		//os comandos de desenho vão pro buffer que aparecia antes. Depois troca
		//de novo e troca troca troca troca... Por isso que chama "double
		//buffering". A janela do SDL com OpenGL por padrão é criada com o
		//double buffer. Prático, né?
		SDL_GL_SwapBuffers();
		//Isso é só pra fazer o programa não gastar 100% de CPU pra uma coisa
		//tão simples. 
		SDL_Delay(10);
	}

	//Faz a SDL fechar todas as coisas dela
	SDL_Quit();

	//Tchau!
	return 0;
}
Beispiel #17
0
void RendererOpenGL::StopDrawingScene(void) const
{
	SDL_GL_SwapBuffers();
}
void SDLWindow::showFrame() {
	SDL_GL_SwapBuffers();
}
Beispiel #19
0
/*
 * r_drawFrame
 * Perform any drawing and setup necessary to produce a single frame.
 */
static void r_drawFrame()
{

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	r_setupModelviewRotate();

	glClear(GL_DEPTH_BUFFER_BIT);

    // Just in case we set all vertices to white.
    glColor4f(1,1,1,1);

    glBindTexture(GL_TEXTURE_2D, textureStars);

    // Render the front quad
    glBegin(GL_QUADS);
        glTexCoord2f(0, 0); glVertex3f(  1.0f, -1.0f, -1.0f );
        glTexCoord2f(1, 0); glVertex3f( -1.0f, -1.0f, -1.0f );
        glTexCoord2f(1, 1); glVertex3f( -1.0f,  1.0f, -1.0f );
        glTexCoord2f(0, 1); glVertex3f(  1.0f,  1.0f, -1.0f );
    glEnd();

    // Render the left quad
    glBegin(GL_QUADS);
        glTexCoord2f(0, 0); glVertex3f(  1.0f, -1.0f,  1.0f );
        glTexCoord2f(1, 0); glVertex3f(  1.0f, -1.0f, -1.0f );
        glTexCoord2f(1, 1); glVertex3f(  1.0f,  1.0f, -1.0f );
        glTexCoord2f(0, 1); glVertex3f(  1.0f,  1.0f,  1.0f );
    glEnd();

    // Render the back quad
    glBegin(GL_QUADS);
        glTexCoord2f(0, 0); glVertex3f( -1.0f, -1.0f,  1.0f );
        glTexCoord2f(1, 0); glVertex3f(  1.0f, -1.0f,  1.0f );
        glTexCoord2f(1, 1); glVertex3f(  1.0f,  1.0f,  1.0f );
        glTexCoord2f(0, 1); glVertex3f( -1.0f,  1.0f,  1.0f );
    glEnd();

    // Render the right quad
    glBegin(GL_QUADS);
        glTexCoord2f(0, 0); glVertex3f( -1.0f, -1.0f, -1.0f );
        glTexCoord2f(1, 0); glVertex3f( -1.0f, -1.0f,  1.0f );
        glTexCoord2f(1, 1); glVertex3f( -1.0f,  1.0f,  1.0f );
        glTexCoord2f(0, 1); glVertex3f( -1.0f,  1.0f, -1.0f );
    glEnd();

    // Render the top quad
    glBegin(GL_QUADS);
        glTexCoord2f(0, 1); glVertex3f( -1.0f,  1.0f, -1.0f );
        glTexCoord2f(0, 0); glVertex3f( -1.0f,  1.0f,  1.0f );
        glTexCoord2f(1, 0); glVertex3f(  1.0f,  1.0f,  1.0f );
        glTexCoord2f(1, 1); glVertex3f(  1.0f,  1.0f, -1.0f );
    glEnd();

    // Render the bottom quad
    glBegin(GL_QUADS);
        glTexCoord2f(0, 0); glVertex3f( -1.0f, -1.0f, -1.0f );
        glTexCoord2f(0, 1); glVertex3f( -1.0f, -1.0f,  1.0f );
        glTexCoord2f(1, 1); glVertex3f(  1.0f, -1.0f,  1.0f );
        glTexCoord2f(1, 0); glVertex3f(  1.0f, -1.0f, -1.0f );
    glEnd();

	glClear(GL_DEPTH_BUFFER_BIT);

    r_setupModelviewTranslate();


	renderer_model_drawASE(0);

	glBindTexture(GL_TEXTURE_2D, textureLava);
    glBegin(GL_QUADS);
    glTexCoord2f(0,0); glVertex3f(200,-201,200);
    glTexCoord2f(1,0); glVertex3f(200,-201,-200);
    glTexCoord2f(1,1); glVertex3f(-200,-201,-200);
    glTexCoord2f(0,1); glVertex3f(-200,-201,200);
    glEnd();

    glBindTexture(GL_TEXTURE_2D, textureScore);
    glBegin(GL_QUADS);
    glTexCoord2f(0,0); glVertex3f(20,-200,20);
    glTexCoord2f(1,0); glVertex3f(20,-200,120);
    glTexCoord2f(1,1); glVertex3f(120,-200,120);
    glTexCoord2f(0,1); glVertex3f(120,-200,20);
    glEnd();

    glBindTexture(GL_TEXTURE_2D, textureBrick);

    glBegin(GL_QUADS);
    glTexCoord2f(0,0); glVertex3f(2,-1,2);
    glTexCoord2f(1,0); glVertex3f(2,-1,-2);
    glTexCoord2f(1,1); glVertex3f(-2,-1,-2);
    glTexCoord2f(0,1); glVertex3f(-2,-1,2);
    glEnd();

    glBegin(GL_QUADS);
    glTexCoord2f(0,0); glVertex3f(randx+size,-100,randz+size);
    glTexCoord2f(size/4,0); glVertex3f(randx+size,-100,randz-size);
    glTexCoord2f(size/4,size/4); glVertex3f(randx-size,-100,randz-size);
    glTexCoord2f(0,size/4); glVertex3f(randx-size,-100,randz+size);
    glEnd();

//	DrawOverlay();
	r_setupModelview();

	glBindTexture(GL_TEXTURE_2D, textureBrick);
//	// Render a square in front of us
//	// Render the front quad
//	glBegin(GL_QUADS);
//	glTexCoord2f(0, 0); glVertex3f(  0.0f, SQRT_2*-0.1f, -0.2f );
//	glTexCoord2f(1, 0); glVertex3f(  0.05f, SQRT_2*-0.1f, -0.1f );
//	glTexCoord2f(1, 1); glVertex3f(  0.05f, SQRT_2*-0.05f, -0.1f );
//	glTexCoord2f(0, 1); glVertex3f(  0.0f, SQRT_2*-0.05f, -0.2f );
//	glEnd();
//	// Render the left quad
//	glBegin(GL_QUADS);
//	glTexCoord2f(0, 0); glVertex3f(  0.15f, SQRT_2*-0.1f, -0.3f );
//	glTexCoord2f(1, 0); glVertex3f(  0.0f, SQRT_2*-0.1f, -0.2f );
//	glTexCoord2f(1, 1); glVertex3f(  0.0f, SQRT_2*-0.05f, -0.2f );
//	glTexCoord2f(0, 1); glVertex3f(  0.15f, SQRT_2*-0.05f, -0.3f );
//	glEnd();
//	// Render the back quad
//	glBegin(GL_QUADS);
//	glTexCoord2f(0, 0); glVertex3f(  0.2f, SQRT_2*-0.1f, -0.2f );
//	glTexCoord2f(1, 0); glVertex3f(  0.15f, SQRT_2*-0.1f, -0.3f );
//	glTexCoord2f(1, 1); glVertex3f(  0.15f, SQRT_2*-0.05f, -0.3f );
//	glTexCoord2f(0, 1); glVertex3f(  0.2f, SQRT_2*-0.05f, -0.2f );
//	glEnd();
//	// Render the right quad
//	glBegin(GL_QUADS);
//	glTexCoord2f(0, 0); glVertex3f(  0.05f, SQRT_2*-0.1f, -0.1f );
//	glTexCoord2f(1, 0); glVertex3f(  0.2f, SQRT_2*-0.1f, -0.2f );
//	glTexCoord2f(1, 1); glVertex3f(  0.2f, SQRT_2*-0.05f, -0.2f );
//	glTexCoord2f(0, 1); glVertex3f(  0.05f, SQRT_2*-0.05f, -0.1f );
//	glEnd();
//	// Render the top quad
//	glBegin(GL_QUADS);
//	glTexCoord2f(0, 0); glVertex3f(  0.05f, SQRT_2*-0.05f, -0.1f );
//	glTexCoord2f(1, 0); glVertex3f(  0.2f, SQRT_2*-0.05f, -0.2f );
//	glTexCoord2f(1, 1); glVertex3f(  0.15f, SQRT_2*-0.05f, -0.3f );
//	glTexCoord2f(0, 1); glVertex3f(  0.0f, SQRT_2*-0.05f, -0.2f );
//	glEnd();
//	// Render the bottom quad
//	glBegin(GL_QUADS);
//	glTexCoord2f(0, 0); glVertex3f(  0.05f, SQRT_2*-0.1f, -0.1f );
//	glTexCoord2f(1, 0); glVertex3f(  0.2f, SQRT_2*-0.1f, -0.2f );
//	glTexCoord2f(1, 1); glVertex3f(  0.15f, SQRT_2*-0.1f, -0.3f );
//	glTexCoord2f(0, 1); glVertex3f(  0.0f, SQRT_2*-0.1f, -0.2f );
//	glEnd();


	SDL_GL_SwapBuffers();
}
static void draw_screen()
{
	static double last_frame_time;
	static int frame_index;
	static float frame_rates[FRAME_INDEX_MAX];
	static float frame_times[FRAME_INDEX_MAX];

	double start_time = time_now_double();

	glClearColor(0.0, 0.0, 0.0, 0.0);

	graph_dev_start_frame();

	sng_set_foreground(WHITE);
	sng_abs_xy_draw_string("F1 FOR HELP", NANO_FONT, SCREEN_WIDTH - 100, 10);

	static struct entity_context *cx;
	if (!cx)
		cx = entity_context_new(50, 50);

	if (wireframe != oldwireframe) {
		oldwireframe = wireframe;
		if (wireframe)
			set_renderer(cx, WIREFRAME_RENDERER | BLACK_TRIS);
		else
			set_renderer(cx, FLATSHADING_RENDERER);
	}

	float r = target_mesh->radius / tan(FOV / 3.0); /* 50% size for middle zoom */
	float r_cam = r * lobby_zoom / 255.0;
	
	camera_set_parameters(cx, 0.1f, r * 2.2, SCREEN_WIDTH, SCREEN_HEIGHT, FOV);
	camera_set_pos(cx, r_cam, 0, 0);
	camera_look_at(cx, 0, 0, 0);
	camera_assign_up_direction(cx, 0, 1, 0);

	union vec3 light_pos = { { 1.01 * r, 0, 0 } };
	quat_rot_vec_self(&light_pos, &light_orientation);
	set_lighting(cx, light_pos.v.x, light_pos.v.y, light_pos.v.z);

	calculate_camera_transform(cx);

	struct entity *e = add_entity(cx, target_mesh, 0, 0, 0, WHITE);
	struct entity *ae = NULL;
	if (planet_mode) {
		update_entity_material(e, &planet_material);
		if (draw_atmosphere) {
			ae = add_entity(cx, atmosphere_mesh, 0, 0, 0, WHITE);
			update_entity_scale(ae, 1.03);
			update_entity_material(ae, &atmosphere_material);
		}
	}
	update_entity_orientation(e, &lobby_orientation);

	if (isDraggingLight) {
		union vec3 light_dir = { { 10.75 * r_cam, 0, 0 } };
		quat_rot_vec_self(&light_dir, &light_orientation);
		sng_set_foreground(WHITE);
		render_line(cx, light_dir.v.x, light_dir.v.y, light_dir.v.z, 0, 0, 0);

		e = add_entity(cx, light_mesh, light_dir.v.x, light_dir.v.y, light_dir.v.z, WHITE);
	} else {
		e = add_entity(cx, light_mesh, light_pos.v.x, light_pos.v.y, light_pos.v.z, WHITE);
	}

	render_entities(cx);

	remove_all_entity(cx);

	if (helpmode)
		draw_help_screen(0);

	if (display_frame_stats > 0) {
		float avg_frame_rate = 0;
		float avg_frame_time = 0;
		int i;
		for (i = 0; i < FRAME_INDEX_MAX; i++) {
			avg_frame_rate += frame_rates[i];
			avg_frame_time += frame_times[i];
		}
		avg_frame_rate /= (float)FRAME_INDEX_MAX;
		avg_frame_time /= (float)FRAME_INDEX_MAX;

		sng_set_foreground(WHITE);
		char stat_buffer[30];
		sprintf(stat_buffer, "fps %5.2f", 1.0/avg_frame_rate);
		sng_abs_xy_draw_string(stat_buffer, NANO_FONT, 2, 10);
		sprintf(stat_buffer, "t %0.2f ms", avg_frame_time * 1000.0);
		sng_abs_xy_draw_string(stat_buffer, NANO_FONT, 92, 10);
	}
	if (display_frame_stats > 1)
		graph_dev_display_debug_menu_show();

	graph_dev_end_frame();

	glFinish();

	/*
	 * Swap the buffers. This this tells the driver to
	 * render the next frame from the contents of the
	 * back-buffer, and to set all rendering operations
	 * to occur on what was the front-buffer.
	 *
	 * Double buffering prevents nasty visual tearing
	 * from the application drawing on areas of the
	 * screen that are being updated at the same time.
	 */
	SDL_GL_SwapBuffers();

	if (display_frame_stats > 0) {
		double end_time = time_now_double();

		frame_rates[frame_index] = start_time - last_frame_time;
		frame_times[frame_index] = end_time - start_time;
		frame_index = (frame_index + 1) % FRAME_INDEX_MAX;
		last_frame_time = start_time;
	}
}
Beispiel #21
0
int main(int argc,char* argv[])
{
  SDL_Surface *screen;
  SDL_Surface *ball_bmp;

  struct ball red_ball, blue_ball;

  SDL_TimerID timer, timer2;

  int done;

  init(&screen);

  /* Load the BMP file into a surface */
  red_ball.ball_bmp = SDL_LoadBMP("ball.bmp");
  if (red_ball.ball_bmp == NULL) {
    fprintf(stderr, "Couldn't load %s: %sn", "ball.bmp", SDL_GetError());
    exit(1);
  }

  /* Load the BMP file into a surface */
  blue_ball.ball_bmp = SDL_LoadBMP("ball2.bmp");
  if (blue_ball.ball_bmp == NULL) {
    fprintf(stderr, "Couldn't load %s: %sn", "ball2.bmp", SDL_GetError());
    exit(1);
  }


  /*
   * Palettized screen modes will have a default palette (a standard
   * 8*8*4 colour cube), but if the image is palettized as well we can
   * use that palette for a nicer colour matching.
   * */
			         
  if (red_ball.ball_bmp->format->palette && screen->format->palette) {
    SDL_SetColors(screen, ball_bmp->format->palette->colors, 0, ball_bmp->format->palette->ncolors);
  }

  /* Blit onto the screen surface */
  if(SDL_BlitSurface(red_ball.ball_bmp, NULL, screen, NULL) < 0)
    fprintf(stderr, "BlitSurface error: %sn", SDL_GetError());

  if(SDL_BlitSurface(blue_ball.ball_bmp, NULL, screen, NULL) < 0)
      fprintf(stderr, "BlitSurface error: %sn", SDL_GetError());

  SDL_UpdateRect(screen, 0, 0, red_ball.ball_bmp->w, red_ball.ball_bmp->h);

  //This could be put in an init function:
  red_ball.startx=0; red_ball.starty=0; red_ball.destx=0; red_ball.desty=0;
  red_ball.x = (float)red_ball.startx; red_ball.y = (float)red_ball.starty;
  red_ball.dx = 0.0; red_ball.dy = 0.0;
  red_ball.screen = screen;

  blue_ball.startx=0; blue_ball.starty=0; blue_ball.destx=0; blue_ball.desty=0;
  blue_ball.x = (float)blue_ball.startx; blue_ball.y = (float)blue_ball.starty;
  blue_ball.dx = 0.0; blue_ball.dy = 0.0;
  blue_ball.screen = screen;


  glClearColor(0, 0, 0, 0);
  glClearDepth(1.0f);
  glViewport(0, 0, 640, 480);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(0, 640, 480, 0, 1, -1);
  glMatrixMode(GL_MODELVIEW);
  glEnable(GL_TEXTURE_2D);
  glLoadIdentity();

  glBegin(GL_QUADS);
    glColor3f(1, 0, 0); glVertex3f(0, 0, 0);
    glColor3f(1, 1, 0); glVertex3f(100, 0, 0);
    glColor3f(1, 0, 1); glVertex3f(100, 100, 0);
    glColor3f(1, 1, 1); glVertex3f(0, 100, 0);
  glEnd();

  SDL_GL_SwapBuffers();


  timer = SDL_AddTimer(20, move_ball, &red_ball);
  SDL_Delay(10);
  timer2 = SDL_AddTimer(20, move_ball, &blue_ball);

  /*Handle the keyboards events here. Catch the SDL_Quit event to exit*/
  done = 0;
  while (!done)
  {
    SDL_Event event;

    /* Check for events */
    while (SDL_PollEvent (&event))
    {
      switch (event.type)
      {
        case SDL_KEYDOWN:
	  break;

        case SDL_MOUSEBUTTONDOWN: 
	{
          switch(event.button.button) 
	  {
	    case SDL_BUTTON_LEFT: 
	    {
	      
              red_ball.destx = event.button.x;
	      red_ball.desty = event.button.y;

	      red_ball.dx = (red_ball.destx - red_ball.x)/50.0;
	      red_ball.dy = (red_ball.desty - red_ball.y)/50.0;

	      break;
	    }

	    case SDL_BUTTON_RIGHT:
	    {
              blue_ball.destx = event.button.x;
	      blue_ball.desty = event.button.y;

	      blue_ball.dx = (blue_ball.destx - blue_ball.x)/50.0;
	      blue_ball.dy = (blue_ball.desty - blue_ball.y)/50.0;

	      break;
	    }

	  }
	}
	break;

	case SDL_QUIT:
	  done = 1;
	  break;

	default:
	  break;

      }
    } 
  }

  /* Free the allocated surface*/
  SDL_FreeSurface(red_ball.ball_bmp);
  SDL_FreeSurface(blue_ball.ball_bmp);

}
Beispiel #22
0
static void wrap_SDL_GL_SwapBuffers(void* ret, void* const* args)
{
    (void)ret; (void)args;
    SDL_GL_SwapBuffers();
}
Beispiel #23
0
/* Here goes our drawing code */
int drawGLScene( GLvoid )
{
	SDL_Delay(1.0f / 60.0f * 1024);

	    /* These are to calculate our fps */
    static GLint T0     = 0;
    static GLint Frames = 0;

    /* Clear The Screen And The Depth Buffer */
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

    /* Move Into The Screen 5 Units */
    glLoadIdentity( );
    glTranslatef( 0.0f, 0.0f, -15.0f );

    //glRotatef( xrot, 1.0f, 0.0f, 0.0f); /* Rotate On The X Axis */
    
	glRotatef( yrot, 0.0f, 1.0f, 0.0f); /* Rotate On The Y Axis */
    //glRotatef( zrot, 0.0f, 0.0f, 1.0f); /* Rotate On The Z Axis */

    /* Select Our Texture */
    glBindTexture( GL_TEXTURE_2D, texture[0] );

    /* NOTE:
     *   The x coordinates of the glTexCoord2f function need to inverted
     * for SDL because of the way SDL_LoadBmp loads the data. So where
     * in the tutorial it has glTexCoord2f( 1.0f, 0.0f ); it should
     * now read glTexCoord2f( 0.0f, 0.0f );
     */
     for(int i=-10;i<10;i++){
     
     	if(i == 0){
     		glColor3f(1,0,0);
     	}else{
     		glColor3f(1,1,1);
 		}
     
     	glPushMatrix();
     	glTranslatef( i*3, 0.0f, 0 );
		 
		glBegin(GL_QUADS);
		  /* Front Face */
		  /* Bottom Left Of The Texture and Quad */
		  glTexCoord2f( 0.0f, 1.0f ); glVertex3f( -1.0f, -1.0f, 1.0f );
		  /* Bottom Right Of The Texture and Quad */
		  glTexCoord2f( 1.0f, 1.0f ); glVertex3f(  1.0f, -1.0f, 1.0f );
		  /* Top Right Of The Texture and Quad */
		  glTexCoord2f( 1.0f, 0.0f ); glVertex3f(  1.0f,  1.0f, 1.0f );
		  /* Top Left Of The Texture and Quad */
		  glTexCoord2f( 0.0f, 0.0f ); glVertex3f( -1.0f,  1.0f, 1.0f );

		  /* Back Face */
		  /* Bottom Right Of The Texture and Quad */
		  glTexCoord2f( 0.0f, 0.0f ); glVertex3f( -1.0f, -1.0f, -1.0f );
		  /* Top Right Of The Texture and Quad */
		  glTexCoord2f( 0.0f, 1.0f ); glVertex3f( -1.0f,  1.0f, -1.0f );
		  /* Top Left Of The Texture and Quad */
		  glTexCoord2f( 1.0f, 1.0f ); glVertex3f(  1.0f,  1.0f, -1.0f );
		  /* Bottom Left Of The Texture and Quad */
		  glTexCoord2f( 1.0f, 0.0f ); glVertex3f(  1.0f, -1.0f, -1.0f );

		  /* Top Face */
		  /* Top Left Of The Texture and Quad */
		  glTexCoord2f( 1.0f, 1.0f ); glVertex3f( -1.0f,  1.0f, -1.0f );
		  /* Bottom Left Of The Texture and Quad */
		  glTexCoord2f( 1.0f, 0.0f ); glVertex3f( -1.0f,  1.0f,  1.0f );
		  /* Bottom Right Of The Texture and Quad */
		  glTexCoord2f( 0.0f, 0.0f ); glVertex3f(  1.0f,  1.0f,  1.0f );
		  /* Top Right Of The Texture and Quad */
		  glTexCoord2f( 0.0f, 1.0f ); glVertex3f(  1.0f,  1.0f, -1.0f );

		  /* Bottom Face */
		  /* Top Right Of The Texture and Quad */
		  glTexCoord2f( 0.0f, 1.0f ); glVertex3f( -1.0f, -1.0f, -1.0f );
		  /* Top Left Of The Texture and Quad */
		  glTexCoord2f( 1.0f, 1.0f ); glVertex3f(  1.0f, -1.0f, -1.0f );
		  /* Bottom Left Of The Texture and Quad */
		  glTexCoord2f( 1.0f, 0.0f ); glVertex3f(  1.0f, -1.0f,  1.0f );
		  /* Bottom Right Of The Texture and Quad */
		  glTexCoord2f( 0.0f, 0.0f ); glVertex3f( -1.0f, -1.0f,  1.0f );

		  /* Right face */
		  /* Bottom Right Of The Texture and Quad */
		  glTexCoord2f( 0.0f, 0.0f ); glVertex3f( 1.0f, -1.0f, -1.0f );
		  /* Top Right Of The Texture and Quad */
		  glTexCoord2f( 0.0f, 1.0f ); glVertex3f( 1.0f,  1.0f, -1.0f );
		  /* Top Left Of The Texture and Quad */
		  glTexCoord2f( 1.0f, 1.0f ); glVertex3f( 1.0f,  1.0f,  1.0f );
		  /* Bottom Left Of The Texture and Quad */
		  glTexCoord2f( 1.0f, 0.0f ); glVertex3f( 1.0f, -1.0f,  1.0f );

		  /* Left Face */
		  /* Bottom Left Of The Texture and Quad */
		  glTexCoord2f( 1.0f, 0.0f ); glVertex3f( -1.0f, -1.0f, -1.0f );
		  /* Bottom Right Of The Texture and Quad */
		  glTexCoord2f( 0.0f, 0.0f ); glVertex3f( -1.0f, -1.0f,  1.0f );
		  /* Top Right Of The Texture and Quad */
		  glTexCoord2f( 0.0f, 1.0f ); glVertex3f( -1.0f,  1.0f,  1.0f );
		  /* Top Left Of The Texture and Quad */
		  glTexCoord2f( 1.0f, 1.0f ); glVertex3f( -1.0f,  1.0f, -1.0f );
		glEnd( );
		
		glPopMatrix();
	}

    /* Draw it to the screen */
    SDL_GL_SwapBuffers( );

    /* Gather our frames per second */
    Frames++;
    {
	GLint t = SDL_GetTicks();
	if (t - T0 >= 5000) {
	    GLfloat seconds = (t - T0) / 1000.0;
	    GLfloat fps = Frames / seconds;
	    printf("%d frames in %g seconds = %g FPS\n", Frames, seconds, fps);
	    T0 = t;
	    Frames = 0;
	}
    }
    
    if(rotate){

		xrot += 0.3f; /* X Axis Rotation */
		yrot += 0.2f; /* Y Axis Rotation */
		zrot += 0.4f; /* Z Axis Rotation */
	}
	
    return( TRUE );
}
int main( int argc, char *argv[] )
{
  printf("It's dangerous to go alone! Take this.\n" );
    
    printf("Game Data Dir: %s\n", getResourceDir().c_str() );
    
	// Initialize SDL
	if (SDL_Init( SDL_INIT_NOPARACHUTE | SDL_INIT_VIDEO ) < 0 ) 
	{
		printf("Unable to init SDL: %s\n", SDL_GetError() );
		exit(1);
	}
    
	// cheezy check for fullscreen
	Uint32 mode_flags = SDL_OPENGL;
	for (int i=1; i < argc; i++)
	{
		if (!_stricmp( argv[i], "-fullscreen"))
		{
			mode_flags |= SDL_FULLSCREEN;
		}
	}
    
    // TODO: flag to control this
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
	SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, 4 );

    
	if (SDL_SetVideoMode( 800, 600, 32, mode_flags ) == 0 ) 
	{
		printf( "Unable to set video mode: %s\n", SDL_GetError() ) ;
		exit(1);
	}
    
	SDL_WM_SetCaption( "Take This.", NULL );

    // Initialize resources
    TakeThisGame *game = new TakeThisGame();
    game->init();   
    
    atexit( TakeThisGame::shutdown );  
    
    // init graphics
    glViewport( 0, 0, 800, 600 );    
    
	//=====[ Main loop ]======
	bool done = false;
	Uint32 ticks = SDL_GetTicks(), ticks_elapsed, sim_ticks = 0;
	float lookMoveX, lookMoveY;
	while(!done)
	{
		SDL_Event event;
        
		while (SDL_PollEvent( &event ) ) 
		{
			switch (event.type )
			{
				case SDL_KEYDOWN:
					switch( event.key.keysym.sym ) 
                {						
                    case SDLK_ESCAPE:
                        done = true;
                        break;

                    default:
                        game->keypress( event.key.keysym.sym );
                        break;
                }
                    break;
                    
				case SDL_MOUSEMOTION:	
                    game->mouseMotion( event.motion.xrel, event.motion.yrel ); 
					break;

				case SDL_MOUSEBUTTONDOWN:					
					//game->mouse( event.button );
					break;
                    
				case SDL_MOUSEBUTTONUP:					
					//game->mouse( event.button );
					break;				
                    
				case SDL_QUIT:
					done = true;
					break;
                    
                default:
                    break;
			}
		}
        
        // Do continuous keys
		Uint8 *keyState = SDL_GetKeyState( NULL );
        
		// convert to btn mask
		Uint32 btnMask = 0;
		btnMask |= (keyState[SDLK_LEFT]||keyState[SDLK_a])?BTN_LEFT:0;
		btnMask |= (keyState[SDLK_RIGHT]||keyState[SDLK_d])?BTN_RIGHT:0;
        
		btnMask |= (keyState[SDLK_UP]||keyState[SDLK_w])?BTN_UP:0;
		btnMask |= (keyState[SDLK_DOWN]||keyState[SDLK_s])?BTN_DOWN:0;
        
		btnMask |= (keyState[SDLK_z]||keyState[SDLK_COMMA])?BTN_A:0;
		btnMask |= (keyState[SDLK_x]||keyState[SDLK_PERIOD])?BTN_B:0;
        
		game->updateButtons( btnMask );
		
		
		// Timing
		ticks_elapsed = SDL_GetTicks() - ticks;
		ticks += ticks_elapsed;
        
		// fixed sim update
		sim_ticks += ticks_elapsed;
		while (sim_ticks > STEPTIME) 
		{
			sim_ticks -= STEPTIME;						
            
			//printf("update sim_ticks %d ticks_elapsed %d\n", sim_ticks, ticks_elapsed );
			game->updateSim( (float)STEPTIME / 1000.0f );			
		}	
        
		// redraw as fast as possible		
		float dtRaw = (float)(ticks_elapsed) / 1000.0f;
        
		game->updateFree( dtRaw ); 
        game->redraw();        
        
		SDL_GL_SwapBuffers();
        
		// Call this once a frame if using tweakables
        //ReloadChangedTweakableValues();        
	}
    
    
    
    return 1;
    
};
Beispiel #25
0
//============================================================================
int main( int argc, char *argv[] )
{	
    
    printf("Game Data Dir: %s\n", getResourceDir().c_str() );
	// Initialize SDL
	if (SDL_Init( SDL_INIT_NOPARACHUTE | SDL_INIT_VIDEO ) < 0 ) 
	{
		fprintf( stderr, "Unable to init SDL: %s\n", SDL_GetError() );
	}

	if (SDL_SetVideoMode( SCREEN_RES_X, SCREEN_RES_Y, 32, SDL_OPENGL /* | SDL_FULLSCREEN */  ) == 0 ) 
	{
		fprintf(stderr,	"Unable to set video mode: %s\n", SDL_GetError());
        exit(1);
	}

	SDL_WM_SetCaption( "LD13 Crossroads", NULL );

	// seed rand
	srand( time(0) );

	// Game
	GameState game;
	game.nextLevel();
	GameViewGL gameView( &game );

	//=====[ Main loop ]======
	Uint32 ticks = SDL_GetTicks(), ticks_elapsed, sim_ticks = 0;
	bool done = false;
	while(!done)
	{
		SDL_Event event;

		while (SDL_PollEvent( &event ) ) 
		{
			switch (event.type )
			{
				case SDL_KEYDOWN:
					switch( event.key.keysym.sym ) 
					{						
						case SDLK_ESCAPE:
								game.cancelWord();
								break;

						case SDLK_RETURN:
						case SDLK_SPACE:
								game.commitWord();
								break;	
						case SDLK_r:
							game.restartLevel();
							break;
						case SDLK_n:
							game.nextLevel();
							break;
                        default:
                            break;
					}
					break;
				case SDL_MOUSEMOTION:
					gameView.mouseMove( event.motion.x, event.motion.y );					
					break;
				case SDL_MOUSEBUTTONDOWN:
					gameView.mouseDown();
					break;
				case SDL_MOUSEBUTTONUP:
					gameView.mouseUp();
					break;
				case SDL_QUIT:
					done = true;
					break;
			}
		}

		// Timing
		ticks_elapsed = SDL_GetTicks() - ticks;
		ticks += ticks_elapsed;

		// fixed sim update
		sim_ticks += ticks_elapsed;
		while (sim_ticks > STEPTIME) 
		{
			sim_ticks -= STEPTIME;						

//			printf("update sim_ticks %d ticks_elapsed %d\n", sim_ticks, ticks_elapsed );			
			game.update( (float)STEPTIME / 1000.0f );
		}	

		// redraw as fast as possible		
		float dtRaw = (float)(ticks_elapsed) / 1000.0f;
		//_RPT2( _CRT_WARN, "ticks_elapsed %d dtraw %f\n", ticks_elapsed, dtRaw );
		gameView.update( dtRaw ); 
		gameView.redraw( dtRaw );

		SDL_GL_SwapBuffers();
	}

	SDL_Quit();

	return 0;
}
Beispiel #26
0
void render_gl()
{
  const glVec WHITE_COLOR(1.0f,1.0f,1.0f,1.0f);
  const glVec GREY_COLOR(0.6f,0.6f,0.6f,0.6f);
  const glVec I_COLOR(1.0f,0.0f,0.0f,1.0f);
  const glVec J_COLOR(0.0f,1.0f,0.0f,1.0f);
  const glVec L_COLOR(0.0f,0.0f,1.0f,1.0f);
  const glVec O_COLOR(1.0f,1.0f,0.0f,1.0f);
  const glVec S_COLOR(1.0f,0.0f,1.0f,1.0f);
  const glVec T_COLOR(0.0f,1.0f,1.0f,1.0f);
  const glVec Z_COLOR(0.5f,1.0f,0.5f,1.0f);

  const DataBuffer &gameState=GAME_STATE.buffer.swap_and_read();

  SDL_GL_SwapBuffers();
  printGlError();

  
  glClear(GL_COLOR_BUFFER_BIT);

  // Draw blocks set in field
  glUniform4fv(GL_STATE.tintUniform, 1, GREY_COLOR.data);
  for(unsigned i=0;i<FIELD_WIDTH;++i)
    {
      for(unsigned j=0;j<FIELD_VIEW_HEIGHT;++j)
	{
	  if(gameState.field.get(i,j))
	    {
	      glUniform2f(GL_STATE.offsetUniform,(GLfloat)i,(GLfloat)j);
	      glDrawElements(GL_TRIANGLES,6,GL_UNSIGNED_SHORT,0);
	    }
	}
    }
  
  // Draw current piece
  arrayt blocks=gameState.current.getBlocks();
  switch(gameState.current.getType())
    {
    case I:
      glUniform4fv(GL_STATE.tintUniform, 1, I_COLOR.data);
      break;
    case J:
      glUniform4fv(GL_STATE.tintUniform, 1, J_COLOR.data);
      break;
    case L:
      glUniform4fv(GL_STATE.tintUniform, 1, L_COLOR.data);
      break;
    case O:
      glUniform4fv(GL_STATE.tintUniform, 1, O_COLOR.data);
      break;
    case S:
      glUniform4fv(GL_STATE.tintUniform, 1, S_COLOR.data);
      break;
    case T:
      glUniform4fv(GL_STATE.tintUniform, 1, T_COLOR.data);
      break;
    case Z:
      glUniform4fv(GL_STATE.tintUniform, 1, Z_COLOR.data);
      break;
    default:
      std::cerr << "Unhandled case in enumerated switch statement!\n";
      break;
    }

  for(auto block : blocks)
    {
      glUniform2f(GL_STATE.offsetUniform,(GLfloat)block.x,(GLfloat)block.y);
      glDrawElements(GL_TRIANGLES,6,GL_UNSIGNED_SHORT,0);
    }

}
Beispiel #27
0
static void Frame()
{
	g_Profiler2.RecordFrameStart();
	PROFILE2("frame");
	g_Profiler2.IncrementFrameNumber();
	PROFILE2_ATTR("%d", g_Profiler2.GetFrameNumber());

	ogl_WarnIfError();

	// get elapsed time
	const double time = timer_Time();
	g_frequencyFilter->Update(time);
	// .. old method - "exact" but contains jumps
#if 0
	static double last_time;
	const double time = timer_Time();
	const float TimeSinceLastFrame = (float)(time-last_time);
	last_time = time;
	ONCE(return);	// first call: set last_time and return

	// .. new method - filtered and more smooth, but errors may accumulate
#else
	const float realTimeSinceLastFrame = 1.0 / g_frequencyFilter->SmoothedFrequency();
#endif
	ENSURE(realTimeSinceLastFrame > 0.0f);

	// decide if update/render is necessary
	bool need_render = !g_app_minimized;
	bool need_update = true;

	// If we are not running a multiplayer game, disable updates when the game is
	// minimized or out of focus and relinquish the CPU a bit, in order to make 
	// debugging easier.
	if(g_PauseOnFocusLoss && !g_NetClient && !g_app_has_focus)
	{
		PROFILE3("non-focus delay");
		need_update = false;
		// don't use SDL_WaitEvent: don't want the main loop to freeze until app focus is restored
		SDL_Delay(10);
	}

	// TODO: throttling: limit update and render frequency to the minimum.
	// this is mostly relevant for "inactive" state, so that other windows
	// get enough CPU time, but it's always nice for power+thermal management.

	bool is_building_archive = ProgressiveBuildArchive();

	// this scans for changed files/directories and reloads them, thus
	// allowing hotloading (changes are immediately assimilated in-game).
	// must not be done during archive building because it changes the
	// archive file each iteration, but keeps it locked; reloading
	// would trigger a warning because the file can't be opened.
	if(!is_building_archive)
		ReloadChangedFiles();

	ProgressiveLoad();

	RendererIncrementalLoad();

	PumpEvents();

	// if the user quit by closing the window, the GL context will be broken and
	// may crash when we call Render() on some drivers, so leave this loop
	// before rendering
	if (quit)
		return;

	// respond to pumped resize events
	if (g_ResizedW || g_ResizedH)
	{
		g_VideoMode.ResizeWindow(g_ResizedW, g_ResizedH);
		g_ResizedW = g_ResizedH = 0;
	}

	if (g_NetClient)
		g_NetClient->Poll();

	ogl_WarnIfError();

	g_GUI->TickObjects();

	ogl_WarnIfError();

	if (g_Game && g_Game->IsGameStarted() && need_update)
	{
		g_Game->Update(realTimeSinceLastFrame);

		g_Game->GetView()->Update(float(realTimeSinceLastFrame));
	}

	// Immediately flush any messages produced by simulation code
	if (g_NetClient)
		g_NetClient->Flush();

	g_UserReporter.Update();

	g_Console->Update(realTimeSinceLastFrame);

	ogl_WarnIfError();
	if(need_render)
	{
		Render();

		PROFILE3("swap buffers");
#if SDL_VERSION_ATLEAST(2, 0, 0)
		SDL_GL_SwapWindow(g_VideoMode.GetWindow());
#else
		SDL_GL_SwapBuffers();
#endif
	}
	ogl_WarnIfError();

	g_Profiler.Frame();

	g_GameRestarted = false;
}
Beispiel #28
0
/* Renders the frame and calls calcFps() */
static void render(RenderConf *rc)
{
	double ws = world.worldSize;
	RenderMat3 m3;
	double m4[16];

	calcFps();

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	/* 3D */
	renderSet3D();

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	mat3_from_quat(m3, quat_conjugate(cam_orientation));
	mat4_from_mat3(m4, m3);
	glMultMatrixd(m4);
	glTranslatef(-cam_position.x, -cam_position.y, -cam_position.z);

	if (autorotate)
		camOrbit(5, 0);

	if (renderSPGridBoxes)
		renderBoxes(rc->numBoxes);

	if (renderWorldLoops) {
		/* Line loops for world box */
		glColor3f(0.0, 1.0, 0.0);
		glBegin(GL_LINE_LOOP);
			glVertex3f(-ws/2, -ws/2, -ws/2);
			glVertex3f(-ws/2, -ws/2, +ws/2);
			glVertex3f(-ws/2, +ws/2, +ws/2);
			glVertex3f(-ws/2, +ws/2, -ws/2);
		glEnd();

		glBegin(GL_LINE_LOOP);
			glVertex3f(+ws/2, -ws/2, -ws/2);
			glVertex3f(+ws/2, -ws/2, +ws/2);
			glVertex3f(+ws/2, +ws/2, +ws/2);
			glVertex3f(+ws/2, +ws/2, -ws/2);
		glEnd();
	}


	/* Strands */
	for (int s = 0; s < world.numStrands; s++)
		renderStrand(&world.strands[s], rc);


	/* Text */
	renderSet2D();
	const int n = 64;
	char string[n];

	snprintf(string, n, "T = %lf K", getKineticTemperature());
	renderString(string, 10, 40);

	snprintf(string, n, "t = %lf µs   (dt = %lf fs)",
			getTime() / MICROSECONDS, getIntegratorTimeStep() / FEMTOSECONDS);
	renderString(string, 10, 25);

	int ips;
	double tps;
	getProgressPerSecond(&ips, &tps);
	snprintf(string, n, "ips = %d   (time/min = %lf ns)",
			ips, tps / NANOSECONDS * 60);
	renderString(string, 10, 10);

	glLoadIdentity();
	renderString(fps_string, 10, SCREEN_H - 10);


	StringList *node = strings;
	while (node != NULL) {
		renderString(node->rsc.string, node->rsc.x, node->rsc.y);
		node = node->next;
	}

	SDL_GL_SwapBuffers();

}
Beispiel #29
0
void displaySDL() {
 if (runningSDL)
  SDL_GL_SwapBuffers(); 
}
Beispiel #30
0
void Main::Execute()
{
    if(SDL_Init(SDL_INIT_EVERYTHING) < 0)
    {
    	printf("SDL Failed to init");
        return;
    }

    // Allow the game pads to be polled.
    SDL_JoystickEventState(SDL_IGNORE);
    SDL_EnableUNICODE(1);
    SDL_GL_SetAttribute(SDL_GL_RED_SIZE,        8);
    SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE,      8);
    SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE,       8);
    SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE,      8);

    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE,      16);
    SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE,     32);

    SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE,  	8);
    SDL_GL_SetAttribute(SDL_GL_ACCUM_GREEN_SIZE,    8);
    SDL_GL_SetAttribute(SDL_GL_ACCUM_BLUE_SIZE, 	8);
    SDL_GL_SetAttribute(SDL_GL_ACCUM_ALPHA_SIZE,    8);

    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS,  1);
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES,  2);

    // Done once before maingame loop to force assets to load
    ResetRenderWindow(); // mac setups up OpenGL here
    mDinodeck->ForceReload();
    ResetRenderWindow(); // height + width info loaded

    unsigned int thisTime = 0;
    unsigned int lastTime = 0;
    unsigned int framesPerSecond = 60;
    unsigned int millisecondsPerFrame = 1000 / framesPerSecond;
    unsigned int fpsTicks = 0;

    SDL_Event event;

    while(mRunning)
    {
        // Calculate delta time
        thisTime = SDL_GetTicks(); // returns in milliseconds
        double deltaTime = static_cast<double>((thisTime - lastTime) / 1000); // convert to seconds
        lastTime = thisTime;

        while(SDL_PollEvent(&event))
        {
            OnEvent(&event);
        }

        mDinodeck->Update(deltaTime);

		fpsTicks = SDL_GetTicks() - fpsTicks;
        if (fpsTicks < millisecondsPerFrame)
        {
            SDL_Delay(millisecondsPerFrame - fpsTicks);
        }
    	SDL_GL_SwapBuffers();
    }

    SDL_Quit();

	return;
}