Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/lib/graphics/graphics_engine.cc @ 6778

Last change on this file since 6778 was 6778, checked in by bensch, 18 years ago

trunk: ModelView work…

File size: 17.5 KB
Line 
1/*
2   orxonox - the future of 3D-vertical-scrollers
3
4   Copyright (C) 2004 orx
5
6   This program is free software; you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation; either version 2, or (at your option)
9   any later version.
10
11   ### File Specific:
12   main-programmer: Benjamin Grauer
13   co-programmer: ...
14*/
15
16#define DEBUG_SPECIAL_MODULE DEBUG_MODULE_GRAPHICS
17
18#include "graphics_engine.h"
19#include "resource_manager.h"
20#include "event_handler.h"
21#include "state.h"
22
23#include "world_entity.h"
24
25#include "render_2d.h"
26#include "text_engine.h"
27#include "light.h"
28#include "shader.h"
29#include "debug.h"
30
31#include "parser/ini_parser/ini_parser.h"
32#include "substring.h"
33#include "text.h"
34
35#include "globals.h"
36#include "texture.h"
37
38#include "effects/graphics_effect.h"
39#include "effects/fog_effect.h"
40
41#include "shell_command.h"
42
43#ifdef __WIN32__
44 #include "class_list.h"
45 #include "static_model.h"
46#endif
47using namespace std;
48
49SHELL_COMMAND(wireframe, GraphicsEngine, wireframe);
50
51/**
52 *  standard constructor
53 */
54GraphicsEngine::GraphicsEngine ()
55{
56  this->setClassID(CL_GRAPHICS_ENGINE, "GraphicsEngine");
57  this->setName("GraphicsEngine");
58
59  this->isInit = false;
60
61  this->bDisplayFPS = false;
62  this->minFPS = 9999;
63  this->maxFPS = 0;
64
65  this->geTextCFPS = NULL;
66  this->geTextMaxFPS = NULL;
67  this->geTextMinFPS = NULL;
68
69  this->fullscreenFlag = 0;
70  this->videoFlags = 0;
71  this->screen = NULL;
72
73
74  // Hardware
75  this->hwRenderer = NULL;
76  this->hwVendor = NULL;
77  this->hwVersion = NULL;
78  this->hwExtensions = NULL;
79
80  // initialize the TextEngine
81  TextEngine::getInstance();
82}
83
84/**
85 *  The Pointer to this GraphicsEngine
86*/
87GraphicsEngine* GraphicsEngine::singletonRef = NULL;
88
89/**
90 *  destructs the graphicsEngine.
91*/
92GraphicsEngine::~GraphicsEngine ()
93{
94  // delete what has to be deleted here
95  delete this->geTextCFPS;
96  delete this->geTextMaxFPS;
97  delete this->geTextMinFPS;
98
99  delete[] this->hwRenderer;
100  delete[] this->hwVendor;
101  delete[] this->hwVersion;
102  delete this->hwExtensions;
103
104  //TextEngine
105  delete TextEngine::getInstance();
106  // render 2D
107  delete Render2D::getInstance();
108
109  SDL_QuitSubSystem(SDL_INIT_VIDEO);
110//   if (this->screen != NULL)
111//     SDL_FreeSurface(this->screen);
112
113  GraphicsEngine::singletonRef = NULL;
114}
115
116/**
117 * initializes the GraphicsEngine with default settings.
118 */
119int GraphicsEngine::init()
120{
121  if (this->isInit)
122    return -1;
123  this->initVideo(640, 480, 16);
124}
125
126/**
127 * loads the GraphicsEngine's settings from a given ini-file and section
128 * @param iniParser the iniParser to load from
129 * @param section the Section in the ini-file to load from
130 * @returns nothing usefull
131 */
132int GraphicsEngine::initFromIniFile(IniParser* iniParser)
133{
134  // looking if we are in fullscreen-mode
135  const char* fullscreen = iniParser->getVar(CONFIG_NAME_FULLSCREEN, CONFIG_SECTION_VIDEO, "0");
136  if (strchr(fullscreen, '1') || !strcasecmp(fullscreen, "true"))
137    this->fullscreenFlag = SDL_FULLSCREEN;
138
139  // looking if we are in fullscreen-mode
140  const char* textures = iniParser->getVar(CONFIG_NAME_TEXTURES, CONFIG_SECTION_VIDEO_ADVANCED, "0");
141  if (strchr(textures, '1') || !strcasecmp(textures, "true"))
142    Texture::setTextureEnableState( true);
143  else
144    Texture::setTextureEnableState(false);
145
146  // searching for a usefull resolution
147  SubString resolution(iniParser->getVar(CONFIG_NAME_RESOLUTION, CONFIG_SECTION_VIDEO, "640x480"), 'x');
148  //resolution.debug();
149
150  this->initVideo(atoi(resolution.getString(0)), atoi(resolution.getString(1)), 16);
151
152  GraphicsEffect* fe = new FogEffect(NULL);
153  this->loadGraphicsEffect(fe);
154  fe->activate();
155  PRINTF(0)("--------------------------------------------------------------\n");
156}
157
158
159
160/**
161 *  initializes the Video for openGL.
162 *
163 * This has to be done only once when starting orxonox.
164 */
165int GraphicsEngine::initVideo(unsigned int resX, unsigned int resY, unsigned int bbp)
166{
167  if (this->isInit)
168    return -1;
169  //   initialize SDL_VIDEO
170  if (SDL_InitSubSystem(SDL_INIT_VIDEO) == -1)
171  {
172    PRINTF(1)("could not initialize SDL Video\n");
173      //      return -1;
174  }
175  // initialize SDL_GL-settings
176  this->setGLattribs();
177
178  // setting the Video Flags.
179  this->videoFlags = SDL_OPENGL | SDL_HWPALETTE | SDL_RESIZABLE | SDL_DOUBLEBUF | SDL_GL_DOUBLEBUFFER;
180
181  /* query SDL for information about our video hardware */
182  const SDL_VideoInfo* videoInfo = SDL_GetVideoInfo ();
183  if( videoInfo == NULL)
184    {
185      PRINTF(1)("Failed getting Video Info :%s\n", SDL_GetError());
186      SDL_Quit ();
187    }
188  if( videoInfo->hw_available)
189    this->videoFlags |= SDL_HWSURFACE;
190  else
191    this->videoFlags |= SDL_SWSURFACE;
192  /*
193  if(VideoInfo -> blit_hw)
194    VideoFlags |= SDL_HWACCEL;
195  */
196    // setting up the Resolution
197  this->setResolution(resX, resY, bbp);
198
199  // GRABBING ALL GL-extensions
200  this->grabHardwareSettings();
201
202  // Enable default GL stuff
203  glEnable(GL_DEPTH_TEST);
204
205  Render2D::getInstance();
206
207  this->isInit = true;
208}
209
210/**
211 * sets the Window Captions and the Name of the icon.
212 * @param windowName The name of the Window
213 * @param icon The name of the Icon on the Disc
214 */
215void GraphicsEngine::setWindowName(const char* windowName, const char* icon)
216{
217  SDL_Surface* iconSurf = SDL_LoadBMP(icon);
218  if (iconSurf != NULL)
219  {
220    Uint32 colorkey = SDL_MapRGB(iconSurf->format, 0, 0, 0);
221    SDL_SetColorKey(iconSurf, SDL_SRCCOLORKEY, colorkey);
222    SDL_WM_SetIcon(iconSurf,NULL);
223    SDL_FreeSurface(iconSurf);
224  }
225
226  SDL_WM_SetCaption (windowName, icon);
227}
228
229
230/**
231 *  Sets the GL-attributes
232 */
233int GraphicsEngine::setGLattribs()
234{
235  // Set video mode
236  // TO DO: parse arguments for settings
237  //SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
238  //SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
239  //SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
240  //SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
241
242
243  SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
244  SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16);
245  SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, 0);
246  SDL_GL_SetAttribute( SDL_GL_ACCUM_RED_SIZE, 0);
247  SDL_GL_SetAttribute( SDL_GL_ACCUM_GREEN_SIZE, 0);
248  SDL_GL_SetAttribute( SDL_GL_ACCUM_BLUE_SIZE, 0);
249  SDL_GL_SetAttribute( SDL_GL_ACCUM_ALPHA_SIZE, 0);
250}
251
252/**
253 * grabs the Hardware Specifics
254 * checks for all the different HW-types
255 */
256void GraphicsEngine::grabHardwareSettings()
257{
258  const char* renderer = (const char*) glGetString(GL_RENDERER);
259  const char* vendor   = (const char*) glGetString(GL_VENDOR);
260  const char* version  = (const char*) glGetString(GL_VERSION);
261  const char* extensions = (const char*) glGetString(GL_EXTENSIONS);
262
263//  printf("%s %s %s\n %s", renderer, vendor, version, extensions);
264
265  if (this->hwRenderer == NULL && renderer != NULL)
266  {
267    this->hwRenderer = new char[strlen(renderer)+1];
268    strcpy(this->hwRenderer, renderer);
269  }
270  if (this->hwVendor == NULL && vendor != NULL)
271  {
272    this->hwVendor = new char[strlen(vendor)+1];
273    strcpy(this->hwVendor, vendor);
274  }
275  if (this->hwVersion == NULL && version != NULL)
276  {
277    this->hwVersion = new char[strlen(version)+11];
278    strcpy(this->hwVersion, version);
279  }
280
281  if (this->hwExtensions == NULL && extensions != NULL)
282    this->hwExtensions = new SubString((char*)glGetString(GL_EXTENSIONS), " \n\t,");
283
284  PRINT(4)("Running on : vendor: %s,  renderer: %s,  version:%s\n", vendor, renderer, version);
285  PRINT(4)("Extensions:\n");
286  if (this->hwExtensions != NULL)
287    for (unsigned int i = 0; i < this->hwExtensions->getCount(); i++)
288      PRINT(4)("%d: %s\n", i, this->hwExtensions->getString(i));
289
290
291  // inizializing GLEW
292  GLenum err = glewInit();
293  if (GLEW_OK != err)
294  {
295    /* Problem: glewInit failed, something is seriously wrong. */
296    PRINTF(1)("%s\n", glewGetErrorString(err));
297  }
298  PRINTF(4)("Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
299}
300
301
302/**
303 *  sets the Resolution of the Screen to display the Graphics to.
304 * @param width The width of the window
305 * @param height The height of the window
306 * @param bpp bits per pixel
307 */
308int GraphicsEngine::setResolution(int width, int height, int bpp)
309{
310  this->resolutionX = width;
311  this->resolutionY = height;
312  this->bitsPerPixel = bpp;
313  State::setResolution( width, height);
314
315  if (this->screen != NULL)
316    SDL_FreeSurface(screen);
317  if((this->screen = SDL_SetVideoMode(this->resolutionX, this->resolutionY, this->bitsPerPixel, this->videoFlags | this->fullscreenFlag)) == NULL)
318    {
319      PRINTF(1)("Could not SDL_SetVideoMode(%d, %d, %d, %d): %s\n", this->resolutionX, this->resolutionY, this->bitsPerPixel, this->videoFlags, SDL_GetError());
320      //    SDL_Quit();
321      //    return -1;
322    }
323    glViewport(0, 0, width, height);                     // Reset The Current Viewport
324
325#ifdef __WIN32__
326    // REBUILDING TEXTURES (ON WINDOWS CONTEXT SWITCH)
327    const std::list<BaseObject*>* texList = ClassList::getList(CL_TEXTURE);
328    if (texList != NULL)
329    {
330      std::list<BaseObject*>::const_iterator reTex;
331      for (reTex = texList->begin(); reTex != texList->end(); reTex++)
332        dynamic_cast<Texture*>(*reTex)->rebuild();
333    }
334    // REBUILDING MODELS
335    const std::list<BaseObject*>* modelList = ClassList::getList(CL_STATIC_MODEL);
336    if (texList != NULL)
337    {
338      std::list<BaseObject*>::const_iterator reModel;
339      for (reModel = modelList->begin(); reModel != modelList->end(); reModel++)
340        dynamic_cast<StaticModel*>(*reModel)->rebuild();
341    }
342#endif /* __WIN32__ */
343}
344
345/**
346 *  sets Fullscreen mode
347 * @param fullscreen true if fullscreen, false if windowed
348*/
349void GraphicsEngine::setFullscreen(bool fullscreen)
350{
351  if (fullscreen)
352    this->fullscreenFlag = SDL_FULLSCREEN;
353  else
354    this->fullscreenFlag = 0;
355  this->setResolution(this->resolutionX, this->resolutionY, this->bitsPerPixel);
356}
357
358/**
359 *  sets the background color
360 * @param red the red part of the background
361 * @param blue the blue part of the background
362 * @param green the green part of the background
363 * @param alpha the alpha part of the background
364 */
365void GraphicsEngine::setBackgroundColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
366{
367  glClearColor(red, green, blue, alpha);
368}
369
370/**
371 *  Signalhandler, for when the resolution has changed
372 * @param resizeInfo SDL information about the size of the new screen size
373 */
374int GraphicsEngine::resolutionChanged(const SDL_ResizeEvent& resizeInfo)
375{
376  this->setResolution(resizeInfo.w, resizeInfo.h, this->bitsPerPixel);
377}
378
379/**
380 *
381 * @param show if The mouse-cursor should be visible
382 */
383void GraphicsEngine::showMouse(bool show)
384{
385  if (show)
386    SDL_ShowCursor(SDL_ENABLE);
387  else
388    SDL_ShowCursor(SDL_DISABLE);
389}
390
391/**
392 *
393 * @returns The Visinility of the mouse-cursor (true if visible, false if it is invisible)
394 */
395bool GraphicsEngine::isMouseVisible()
396{
397  if (SDL_ShowCursor(SDL_QUERY) == SDL_ENABLE)
398    return true;
399  else
400    return false;
401}
402
403/**
404 *
405 * @param steal If the Winodow-Managers Events should be stolen to this app
406 * (steals the mouse, and all WM-clicks)
407 *
408 * This only happens, if the HARD-Debug-level is set to 0,1,2, because otherwise a Segfault could
409 * result in the loss of System-controll
410 */
411void GraphicsEngine::stealWMEvents(bool steal)
412{
413#if DEBUG < 3
414   if (steal)
415     SDL_WM_GrabInput(SDL_GRAB_ON);
416   else
417     SDL_WM_GrabInput(SDL_GRAB_OFF);
418#endif
419}
420
421/**
422 *
423 * @returns true if Events are stolen from the WM, false if not.
424 */
425bool GraphicsEngine::isStealingEvents()
426{
427   if (SDL_WM_GrabInput(SDL_GRAB_QUERY) == SDL_GRAB_ON)
428     return true;
429   else
430     return false;
431};
432
433/**
434 *  entering 2D Mode
435
436   this is a GL-Projection-mode, that is orthogonal, for placing the font in fron of everything else
437*/
438void GraphicsEngine::enter2DMode()
439{
440  //GraphicsEngine::storeMatrices();
441  SDL_Surface *screen = SDL_GetVideoSurface();
442
443  /* Note, there may be other things you need to change,
444     depending on how you have your OpenGL state set up.
445  */
446  glPushAttrib(GL_ENABLE_BIT);
447  glDisable(GL_DEPTH_TEST);
448  glDisable(GL_CULL_FACE);
449  glDisable(GL_LIGHTING);  // will be set back when leaving 2D-mode
450
451  glMatrixMode(GL_PROJECTION);
452  glPushMatrix();
453  glLoadIdentity();
454  glOrtho(0.0, (GLdouble)screen->w, (GLdouble)screen->h, 0.0, 0.0, 1.0);
455
456  glMatrixMode(GL_MODELVIEW);
457  glPushMatrix();
458  glLoadIdentity();
459}
460
461/**
462 *  leaves the 2DMode again also @see Font::enter2DMode()
463 */
464void GraphicsEngine::leave2DMode()
465{
466  glMatrixMode(GL_PROJECTION);
467  glPopMatrix();
468
469  glMatrixMode(GL_MODELVIEW);
470  glPopMatrix();
471
472  glPopAttrib();
473}
474
475void GraphicsEngine::wireframe()
476{
477  glPolygonMode(GL_FRONT, GL_LINE);
478}
479
480/**
481 *  stores the GL_matrices
482 */
483void GraphicsEngine::storeMatrices()
484{
485  glGetDoublev(GL_PROJECTION_MATRIX, GraphicsEngine::projMat);
486  glGetDoublev(GL_MODELVIEW_MATRIX, GraphicsEngine::modMat);
487  glGetIntegerv(GL_VIEWPORT, GraphicsEngine::viewPort);
488}
489
490//! the stored ModelView Matrix.
491GLdouble GraphicsEngine::modMat[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
492//! the stored Projection Matrix
493GLdouble GraphicsEngine::projMat[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
494//! The ViewPort
495GLint GraphicsEngine::viewPort[4] = {0,0,0,0};
496
497
498
499/**
500 *  outputs all the Fullscreen modes.
501 */
502void GraphicsEngine::listModes()
503{
504  /* Get available fullscreen/hardware modes */
505  this->videoModes=SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_HWSURFACE);
506
507  /* Check is there are any modes available */
508  if(this->videoModes == (SDL_Rect **)0){
509    PRINTF(1)("No modes available!\n");
510    exit(-1);
511  }
512
513  /* Check if our resolution is restricted */
514  if(this->videoModes == (SDL_Rect **)-1){
515    PRINTF(2)("All resolutions available.\n");
516  }
517  else{
518    /* Print valid modes */
519    PRINT(0)("Available Resoulution Modes are\n");
520    for(int i = 0; this->videoModes[i]; ++i)
521      PRINT(4)(" |  %d x %d\n", this->videoModes[i]->w, this->videoModes[i]->h);
522  }
523}
524
525/**
526 * checks wether a certain extension is availiable
527 * @param extension the Extension to check for (ex. GL_ARB_texture_env_dot3)
528 * @return true if it is, false otherwise
529 */
530bool GraphicsEngine::hwSupportsEXT(const char* extension)
531{
532  if (this->hwExtensions != NULL)
533    for (unsigned int i = 0; i < this->hwExtensions->getCount(); i++)
534      if (!strcmp(extension, this->hwExtensions->getString(i)))
535        return true;
536  return false;
537}
538
539/**
540 * updates everything that is to be updated in the GraphicsEngine
541 */
542void GraphicsEngine::update(float dt)
543{
544  Render2D::getInstance()->update(dt);
545}
546
547
548/**
549 *  ticks the Text
550 * @param dt the time passed
551 */
552void GraphicsEngine::tick(float dt)
553{
554  if( unlikely(this->bDisplayFPS))
555  {
556    this->currentFPS = 1.0/dt;
557    if( unlikely(this->currentFPS > this->maxFPS)) this->maxFPS = this->currentFPS;
558    if( unlikely(this->currentFPS < this->minFPS)) this->minFPS = this->currentFPS;
559
560#ifndef NO_TEXT
561      char tmpChar1[20];
562      sprintf(tmpChar1, "Current:  %4.0f", this->currentFPS);
563      this->geTextCFPS->setText(tmpChar1);
564      char tmpChar2[20];
565      sprintf(tmpChar2, "Max:    %4.0f", this->maxFPS);
566      this->geTextMaxFPS->setText(tmpChar2);
567      char tmpChar3[20];
568      sprintf(tmpChar3, "Min:    %4.0f", this->minFPS);
569      this->geTextMinFPS->setText(tmpChar3);
570#endif /* NO_TEXT */
571
572
573  }
574  Render2D::getInstance()->tick(dt);
575}
576
577
578void GraphicsEngine::draw() const
579{
580  GraphicsEngine::storeMatrices();
581
582  LightManager::getInstance()->draw();
583
584  Shader::suspendShader();
585
586  Render2D::getInstance()->draw(E2D_LAYER_ALL);
587  Shader::restoreShader();
588}
589
590void GraphicsEngine::draw(const std::list<WorldEntity*>& drawList ) const
591{
592  std::list<WorldEntity*>::const_iterator entity;
593  for (entity = drawList.begin(); entity != drawList.end(); entity++)
594    if ((*entity)->isVisible())
595      (*entity)->draw();
596}
597
598
599/**
600 * displays the Frames per second
601 * @param display if the text should be displayed
602*/
603void GraphicsEngine::displayFPS(bool display)
604{
605#ifndef NO_TEXT
606  if( display )
607{
608  if (this->geTextCFPS == NULL)
609  {
610    this->geTextCFPS = new Text("fonts/arial_black.ttf", 15);
611    this->geTextCFPS->setName("curFPS");
612    this->geTextCFPS->setAlignment(TEXT_ALIGN_LEFT);
613    this->geTextCFPS->setAbsCoor2D(5, 0);
614  }
615  if (this->geTextMaxFPS == NULL)
616  {
617    this->geTextMaxFPS = new Text("fonts/arial_black.ttf", 15);
618    this->geTextMaxFPS->setName("MaxFPS");
619    this->geTextMaxFPS->setAlignment(TEXT_ALIGN_LEFT);
620    this->geTextMaxFPS->setAbsCoor2D(5, 20);
621  }
622  if (this->geTextMinFPS == NULL)
623  {
624    this->geTextMinFPS = new Text("fonts/arial_black.ttf", 15);
625    this->geTextMinFPS->setName("MinFPS");
626    this->geTextMinFPS->setAlignment(TEXT_ALIGN_LEFT);
627    this->geTextMinFPS->setAbsCoor2D(5, 40);
628  }
629}
630else
631{
632  delete this->geTextCFPS;
633  this->geTextCFPS = NULL;
634  delete this->geTextMaxFPS;
635  this->geTextMaxFPS = NULL;
636  delete this->geTextMinFPS;
637  this->geTextMinFPS = NULL;
638}
639  this->bDisplayFPS = display;
640#else
641  this->bDisplayFPS = false;
642#endif /* NO_TEXT */
643}
644
645
646/**
647  processes the events for the GraphicsEngine class
648* @param the event to handle
649 */
650void GraphicsEngine::process(const Event &event)
651{
652  switch (event.type)
653  {
654    case EV_VIDEO_RESIZE:
655      this->resolutionChanged(event.resize);
656      break;
657  }
658}
659
660
661/**
662 * loads a GraphicsEffect into the engine
663 * @param effect the GraphicsEffect to add
664 */
665bool GraphicsEngine::loadGraphicsEffect(GraphicsEffect* effect)
666{
667  list<GraphicsEffect*>::iterator it;
668  for (it = this->graphicsEffects.begin(); it != this->graphicsEffects.end(); it++)
669    if( (*it) == effect)
670      return false;
671
672  this->graphicsEffects.push_back(effect);
673
674  return true;
675}
676
677
678/**
679 * unloads a GraphicsEffect from the engine
680 * @param effect the GraphicsEffect to remove
681 */
682bool GraphicsEngine::unloadGraphicsEffect(GraphicsEffect* effect)
683{
684  list<GraphicsEffect*>::iterator it;
685  for (it = this->graphicsEffects.begin(); it != this->graphicsEffects.end(); it++)
686  {
687    if( (*it) == effect)
688    {
689      this->graphicsEffects.erase(it);
690      return true;
691    }
692  }
693
694  return false;
695}
696
Note: See TracBrowser for help on using the repository browser.