Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/cd/src/lib/graphics/graphics_engine.cc @ 7537

Last change on this file since 7537 was 7319, checked in by bensch, 19 years ago

orxonox/trunk: MUCH more comprehensive SubString

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