New grow and skid sounds from remaxim
[supertux.git] / src / video / gl_renderer.cpp
1 //  $Id: gl_renderer.cpp 5063 2007-05-27 11:32:00Z matzeb $
2 //
3 //  SuperTux
4 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
5 //
6 //  This program is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU General Public License
8 //  as published by the Free Software Foundation; either version 2
9 //  of the License, or (at your option) any later version.
10 //
11 //  This program is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 //  GNU General Public License for more details.
15 //
16 //  You should have received a copy of the GNU General Public License
17 //  along with this program; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19 #include <config.h>
20
21 #ifdef HAVE_OPENGL
22
23 #include <functional>
24 #include <algorithm>
25 #include <cassert>
26 #include <math.h>
27 #include <iostream>
28 #include <SDL_image.h>
29 #include <sstream>
30 #include <iomanip>
31 #include <physfs.h>
32
33 #include "glutil.hpp"
34 #include "gl_renderer.hpp"
35 #include "gl_texture.hpp"
36 #include "gl_surface_data.hpp"
37 #include "drawing_context.hpp"
38 #include "drawing_request.hpp"
39 #include "surface.hpp"
40 #include "font.hpp"
41 #include "main.hpp"
42 #include "gameconfig.hpp"
43 #include "texture.hpp"
44 #include "texture_manager.hpp"
45 #include "obstack/obstackpp.hpp"
46 #define LIGHTMAP_DIV 5
47
48 #ifdef GL_VERSION_ES_CM_1_0
49 #  define glOrtho glOrthof
50 #endif
51
52 namespace 
53 {
54
55 inline void intern_draw(float left, float top, float right, float bottom,
56                         float uv_left, float uv_top,
57                         float uv_right, float uv_bottom,
58                         float angle, float alpha,
59                         const Color& color,
60                         const Blend& blend,
61                         DrawingEffect effect)
62 {
63   if(effect & HORIZONTAL_FLIP)
64     std::swap(uv_left, uv_right);
65  
66   if(effect & VERTICAL_FLIP) 
67     std::swap(uv_top, uv_bottom);
68
69   // unrotated blit
70   glBlendFunc(blend.sfactor, blend.dfactor);
71   glColor4f(color.red, color.green, color.blue, color.alpha * alpha);
72  
73   if (angle == 0.0f) {
74     float vertices[] = {
75       left, top,
76       right, top,
77       right, bottom,
78       left, bottom,
79     };
80     glVertexPointer(2, GL_FLOAT, 0, vertices);
81
82     float uvs[] = {
83       uv_left, uv_top,
84       uv_right, uv_top,
85       uv_right, uv_bottom,
86       uv_left, uv_bottom,
87     };
88     glTexCoordPointer(2, GL_FLOAT, 0, uvs);
89
90     glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
91   } else {
92     // rotated blit
93     float center_x = (left + right) / 2;
94     float center_y = (top + bottom) / 2;
95
96     float sa = sinf(angle/180.0f*M_PI);
97     float ca = cosf(angle/180.0f*M_PI);
98
99     left  -= center_x;
100     right -= center_x;
101
102     top    -= center_y;
103     bottom -= center_y;
104
105     float vertices[] = {
106         left*ca - top*sa + center_x, left*sa + top*ca + center_y,
107         right*ca - top*sa + center_x, right*sa + top*ca + center_y,
108         right*ca - bottom*sa + center_x, right*sa + bottom*ca + center_y,
109         left*ca - bottom*sa + center_x, left*sa + bottom*ca + center_y
110     };
111     glVertexPointer(2, GL_FLOAT, 0, vertices);
112
113     float uvs[] = {
114       uv_left, uv_top,
115       uv_right, uv_top,
116       uv_right, uv_bottom,
117       uv_left, uv_bottom,
118     };
119     glTexCoordPointer(2, GL_FLOAT, 0, uvs);
120
121     glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
122   }
123
124   // FIXME: find a better way to restore the blend mode
125   glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
126   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
127 }
128
129 }
130
131 namespace GL {
132
133 Renderer::Renderer()
134   : desktop_width(-1),
135     desktop_height(-1)
136 {
137   ::Renderer::instance_ = this;
138
139 #if SDL_MAJOR_VERSION > 1 || SDL_MINOR_VERSION > 2 || (SDL_MINOR_VERSION == 2 && SDL_PATCHLEVEL >= 10)
140   // unfortunately only newer SDLs have these infos.
141   // This must be called before SDL_SetVideoMode() or it will return
142   // the window size instead of the desktop size.
143   const SDL_VideoInfo *info = SDL_GetVideoInfo();
144   if (info)
145     {
146       desktop_width  = info->current_w;
147       desktop_height = info->current_h;     
148     }
149 #endif
150
151   if(texture_manager != 0)
152     texture_manager->save_textures();
153
154 #ifdef SDL_GL_SWAP_CONTROL
155   if(config->try_vsync) {
156     /* we want vsync for smooth scrolling */
157     SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 1);
158   }
159 #endif
160
161   SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
162
163   // FIXME: Hu? 16bit rendering?
164   SDL_GL_SetAttribute(SDL_GL_RED_SIZE,   5);
165   SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
166   SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE,  5);
167
168   int flags = SDL_OPENGL;
169   int width;
170   int height;
171
172   if(config->use_fullscreen)
173     {
174       flags |= SDL_FULLSCREEN;
175       width  = config->fullscreen_width;
176       height = config->fullscreen_height;
177     }
178   else
179     {
180 //      flags |= SDL_RESIZABLE;
181       width  = config->window_width;
182       height = config->window_height;
183     }
184
185   int bpp = 0;
186   SDL_Surface *screen = SDL_SetVideoMode(width, height, bpp, flags);
187
188   if(screen == 0) {
189     std::stringstream msg;
190     msg << "Couldn't set video mode (" << width << "x" << height
191         << "-" << bpp << "bpp): " << SDL_GetError();
192     throw std::runtime_error(msg.str());
193   }
194
195   // setup opengl state and transform
196   glDisable(GL_DEPTH_TEST);
197   glDisable(GL_CULL_FACE);
198   glEnable(GL_TEXTURE_2D);
199   glEnable(GL_BLEND);
200   glEnableClientState(GL_VERTEX_ARRAY);
201   glEnableClientState(GL_TEXTURE_COORD_ARRAY);
202   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
203
204   // Init the projection matrix, viewport and stuff
205   apply_config();
206   
207   if(texture_manager == 0)
208     texture_manager = new TextureManager();
209   else
210     texture_manager->reload_textures();
211 }
212
213 Renderer::~Renderer()
214 {
215 }
216
217 void
218 Renderer::draw_surface(const DrawingRequest& request)
219 {
220   const Surface* surface = (const Surface*) request.request_data;
221   GL::Texture *gltexture = dynamic_cast<GL::Texture *>(surface->get_texture());
222   GL::SurfaceData *surface_data = reinterpret_cast<GL::SurfaceData *>(surface->get_surface_data());
223
224   glBindTexture(GL_TEXTURE_2D, gltexture->get_handle());
225   intern_draw(request.pos.x, request.pos.y,
226               request.pos.x + surface->get_width(),
227               request.pos.y + surface->get_height(),
228               surface_data->get_uv_left(),
229               surface_data->get_uv_top(),
230               surface_data->get_uv_right(),
231               surface_data->get_uv_bottom(),
232               request.angle,
233               request.alpha,
234               request.color,
235               request.blend,
236               request.drawing_effect);
237 }
238
239 void
240 Renderer::draw_surface_part(const DrawingRequest& request)
241 {
242   const SurfacePartRequest* surfacepartrequest
243     = (SurfacePartRequest*) request.request_data;
244   const Surface *surface = surfacepartrequest->surface;
245   GL::Texture *gltexture = dynamic_cast<GL::Texture *>(surface->get_texture());
246   GL::SurfaceData *surface_data = reinterpret_cast<GL::SurfaceData *>(surface->get_surface_data());
247
248   float uv_width = surface_data->get_uv_right() - surface_data->get_uv_left();
249   float uv_height = surface_data->get_uv_bottom() - surface_data->get_uv_top();
250
251   float uv_left = surface_data->get_uv_left() + (uv_width * surfacepartrequest->source.x) / surface->get_width();
252   float uv_top = surface_data->get_uv_top() + (uv_height * surfacepartrequest->source.y) / surface->get_height();
253   float uv_right = surface_data->get_uv_left() + (uv_width * (surfacepartrequest->source.x + surfacepartrequest->size.x)) / surface->get_width();
254   float uv_bottom = surface_data->get_uv_top() + (uv_height * (surfacepartrequest->source.y + surfacepartrequest->size.y)) / surface->get_height();
255
256   glBindTexture(GL_TEXTURE_2D, gltexture->get_handle());
257   intern_draw(request.pos.x, request.pos.y,
258               request.pos.x + surfacepartrequest->size.x,
259               request.pos.y + surfacepartrequest->size.y,
260               uv_left,
261               uv_top,
262               uv_right,
263               uv_bottom,
264               0.0,
265               request.alpha,
266               request.color,
267               Blend(),
268               request.drawing_effect);
269 }
270
271 void
272 Renderer::draw_gradient(const DrawingRequest& request)
273 {
274   const GradientRequest* gradientrequest 
275     = (GradientRequest*) request.request_data;
276   const Color& top = gradientrequest->top;
277   const Color& bottom = gradientrequest->bottom;
278
279   glDisable(GL_TEXTURE_2D);
280   glDisableClientState(GL_TEXTURE_COORD_ARRAY);
281   glEnableClientState(GL_COLOR_ARRAY);
282
283   float vertices[] = {
284     0, 0,
285     SCREEN_WIDTH, 0,
286     SCREEN_WIDTH, SCREEN_HEIGHT,
287     0, SCREEN_HEIGHT
288   };
289   glVertexPointer(2, GL_FLOAT, 0, vertices);
290
291   float colors[] = {
292     top.red, top.green, top.blue, top.alpha,
293     top.red, top.green, top.blue, top.alpha,
294     bottom.red, bottom.green, bottom.blue, bottom.alpha,
295     bottom.red, bottom.green, bottom.blue, bottom.alpha,
296   };
297   glColorPointer(4, GL_FLOAT, 0, colors);
298
299   glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
300
301   glDisableClientState(GL_COLOR_ARRAY);
302   glEnableClientState(GL_TEXTURE_COORD_ARRAY);
303
304   glEnable(GL_TEXTURE_2D);
305   glColor4f(1, 1, 1, 1);
306 }
307
308 void
309 Renderer::draw_filled_rect(const DrawingRequest& request)
310 {
311   const FillRectRequest* fillrectrequest
312     = (FillRectRequest*) request.request_data;
313
314   glDisable(GL_TEXTURE_2D);
315   glColor4f(fillrectrequest->color.red, fillrectrequest->color.green,
316             fillrectrequest->color.blue, fillrectrequest->color.alpha);
317   glDisableClientState(GL_TEXTURE_COORD_ARRAY);
318   
319   if (fillrectrequest->radius != 0.0f)
320     {
321       // draw round rect
322       // Keep radius in the limits, so that we get a circle instead of
323       // just graphic junk
324       float radius = std::min(fillrectrequest->radius,
325                               std::min(fillrectrequest->size.x/2,
326                                        fillrectrequest->size.y/2));
327
328       // inner rectangle
329       Rect irect(request.pos.x    + radius,
330                  request.pos.y    + radius,
331                  request.pos.x + fillrectrequest->size.x - radius,
332                  request.pos.y + fillrectrequest->size.y - radius);
333
334
335       int n = 8;
336       int p = 0;
337       float vertices[(n+1) * 4 * 2];
338
339       for(int i = 0; i <= n; ++i)
340         {
341           float x = sinf(i * (M_PI/2) / n) * radius;
342           float y = cosf(i * (M_PI/2) / n) * radius;
343
344           vertices[p++] = irect.get_left() - x;
345           vertices[p++] = irect.get_top()  - y;
346
347           vertices[p++] = irect.get_right() + x;
348           vertices[p++] = irect.get_top()   - y;
349         }
350
351       for(int i = 0; i <= n; ++i)
352         {
353           float x = cosf(i * (M_PI/2) / n) * radius;
354           float y = sinf(i * (M_PI/2) / n) * radius;
355
356           vertices[p++] = irect.get_left()   - x;
357           vertices[p++] = irect.get_bottom() + y;
358
359           vertices[p++] = irect.get_right()  + x;
360           vertices[p++] = irect.get_bottom() + y;
361         }
362
363       glVertexPointer(2, GL_FLOAT, 0, vertices);
364       glDrawArrays(GL_TRIANGLE_STRIP, 0,  sizeof(vertices)/sizeof(float)/2);
365     }
366   else
367     {
368       float x = request.pos.x;
369       float y = request.pos.y;
370       float w = fillrectrequest->size.x;
371       float h = fillrectrequest->size.y;
372
373       float vertices[] = {
374         x,   y,
375         x+w, y,
376         x+w, y+h,
377         x,   y+h
378       };
379       glVertexPointer(2, GL_FLOAT, 0, vertices);
380
381       glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
382     }
383
384   glEnableClientState(GL_TEXTURE_COORD_ARRAY);
385   glEnable(GL_TEXTURE_2D);
386   glColor4f(1, 1, 1, 1);
387 }
388
389 void
390 Renderer::draw_inverse_ellipse(const DrawingRequest& request)
391 {
392   const InverseEllipseRequest* ellipse = (InverseEllipseRequest*)request.request_data;
393
394   glDisable(GL_TEXTURE_2D);
395   glColor4f(ellipse->color.red,  ellipse->color.green,
396             ellipse->color.blue, ellipse->color.alpha);
397     
398   float x = request.pos.x;
399   float y = request.pos.y;
400   float w = ellipse->size.x/2.0f;
401   float h = ellipse->size.y/2.0f;
402
403   static const int slices = 16;
404   static const int points = (slices+1) * 12;
405
406   float vertices[points * 2];
407   int   p = 0;
408
409   // Bottom
410   vertices[p++] = SCREEN_WIDTH; vertices[p++] = SCREEN_HEIGHT;
411   vertices[p++] = 0;            vertices[p++] = SCREEN_HEIGHT;
412   vertices[p++] = x;            vertices[p++] = y+h;
413
414   // Top
415   vertices[p++] = SCREEN_WIDTH; vertices[p++] = 0;
416   vertices[p++] = 0;            vertices[p++] = 0;
417   vertices[p++] = x;            vertices[p++] = y-h;
418
419   // Left
420   vertices[p++] = SCREEN_WIDTH; vertices[p++] = 0;
421   vertices[p++] = SCREEN_WIDTH; vertices[p++] = SCREEN_HEIGHT;
422   vertices[p++] = x+w;          vertices[p++] = y;
423
424   // Right
425   vertices[p++] = 0;            vertices[p++] = 0;
426   vertices[p++] = 0;            vertices[p++] = SCREEN_HEIGHT;
427   vertices[p++] = x-w;          vertices[p++] = y;
428
429   for(int i = 0; i < slices; ++i)
430     {
431       float ex1 = sinf(M_PI/2 / slices * i) * w;
432       float ey1 = cosf(M_PI/2 / slices * i) * h;
433
434       float ex2 = sinf(M_PI/2 / slices * (i+1)) * w;
435       float ey2 = cosf(M_PI/2 / slices * (i+1)) * h;
436
437       // Bottom/Right
438       vertices[p++] = SCREEN_WIDTH; vertices[p++] = SCREEN_HEIGHT;
439       vertices[p++] = x + ex1;      vertices[p++] = y + ey1;
440       vertices[p++] = x + ex2;      vertices[p++] = y + ey2;
441
442       // Top/Left
443       vertices[p++] = 0;            vertices[p++] = 0;
444       vertices[p++] = x - ex1;      vertices[p++] = y - ey1;
445       vertices[p++] = x - ex2;      vertices[p++] = y - ey2;
446
447       // Top/Right
448       vertices[p++] = SCREEN_WIDTH; vertices[p++] = 0;
449       vertices[p++] = x + ex1;      vertices[p++] = y - ey1;
450       vertices[p++] = x + ex2;      vertices[p++] = y - ey2;
451
452       // Bottom/Left
453       vertices[p++] = 0;            vertices[p++] = SCREEN_HEIGHT;
454       vertices[p++] = x - ex1;      vertices[p++] = y + ey1;
455       vertices[p++] = x - ex2;      vertices[p++] = y + ey2;
456     }
457
458   glDisableClientState(GL_TEXTURE_COORD_ARRAY);
459   glVertexPointer(2, GL_FLOAT, 0, vertices);
460
461   glDrawArrays(GL_TRIANGLES, 0, points);
462
463   glEnableClientState(GL_TEXTURE_COORD_ARRAY);
464
465   glEnable(GL_TEXTURE_2D);
466   glColor4f(1, 1, 1, 1);    
467 }
468
469 void 
470 Renderer::do_take_screenshot()
471 {
472   // [Christoph] TODO: Yes, this method also takes care of the actual disk I/O. Split it?
473
474   SDL_Surface *shot_surf;
475   // create surface to hold screenshot
476 #if SDL_BYTEORDER == SDL_BIG_ENDIAN
477   shot_surf = SDL_CreateRGBSurface(SDL_SWSURFACE, SCREEN_WIDTH, SCREEN_HEIGHT, 24, 0x00FF0000, 0x0000FF00, 0x000000FF, 0);
478 #else
479   shot_surf = SDL_CreateRGBSurface(SDL_SWSURFACE, SCREEN_WIDTH, SCREEN_HEIGHT, 24, 0x000000FF, 0x0000FF00, 0x00FF0000, 0);
480 #endif
481   if (!shot_surf) {
482     log_warning << "Could not create RGB Surface to contain screenshot" << std::endl;
483     return;
484   }
485
486   // read pixels into array
487   char* pixels = new char[3 * SCREEN_WIDTH * SCREEN_HEIGHT];
488   if (!pixels) {
489     log_warning << "Could not allocate memory to store screenshot" << std::endl;
490     SDL_FreeSurface(shot_surf);
491     return;
492   }
493   glReadPixels(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, GL_RGB, GL_UNSIGNED_BYTE, pixels);
494
495   // copy array line-by-line
496   for (int i = 0; i < SCREEN_HEIGHT; i++) {
497     char* src = pixels + (3 * SCREEN_WIDTH * (SCREEN_HEIGHT - i - 1));
498     if(SDL_MUSTLOCK(shot_surf))
499       {
500         SDL_LockSurface(shot_surf);
501       }
502     char* dst = ((char*)shot_surf->pixels) + i * shot_surf->pitch;
503     memcpy(dst, src, 3 * SCREEN_WIDTH);
504     if(SDL_MUSTLOCK(shot_surf))
505       {
506         SDL_UnlockSurface(shot_surf);
507       }
508   }
509
510   // free array
511   delete[](pixels);
512
513   // save screenshot
514   static const std::string writeDir = PHYSFS_getWriteDir();
515   static const std::string dirSep = PHYSFS_getDirSeparator();
516   static const std::string baseName = "screenshot";
517   static const std::string fileExt = ".bmp";
518   std::string fullFilename;
519   for (int num = 0; num < 1000; num++) {
520     std::ostringstream oss;
521     oss << baseName;
522     oss << std::setw(3) << std::setfill('0') << num;
523     oss << fileExt;
524     std::string fileName = oss.str();
525     fullFilename = writeDir + dirSep + fileName;
526     if (!PHYSFS_exists(fileName.c_str())) {
527       SDL_SaveBMP(shot_surf, fullFilename.c_str());
528       log_debug << "Wrote screenshot to \"" << fullFilename << "\"" << std::endl;
529       SDL_FreeSurface(shot_surf);
530       return;
531     }
532   }
533   log_warning << "Did not save screenshot, because all files up to \"" << fullFilename << "\" already existed" << std::endl;
534   SDL_FreeSurface(shot_surf);
535 }
536
537 void
538 Renderer::flip()
539 {
540   assert_gl("drawing");
541   SDL_GL_SwapBuffers();
542 }
543
544 void
545 Renderer::resize(int w, int h)
546 {
547   // This causes the screen to go black, which is annoying, but seems
548   // unavoidable with SDL at the moment
549   SDL_SetVideoMode(w, h, 0, SDL_OPENGL /*| SDL_RESIZABLE*/);
550
551   config->window_width  = w;
552   config->window_height = h;
553
554   apply_config();
555 }
556
557 void
558 Renderer::apply_config()
559 {    
560   if (0)
561     {
562       std::cout << "Applying Config:" 
563                 << "\n  Desktop: " << desktop_width << "x" << desktop_height
564                 << "\n  Window:  " << config->window_width << "x" << config->window_height
565                 << "\n  FullRes: " << config->fullscreen_width << "x" << config->fullscreen_height
566                 << "\n  Aspect:  " << config->aspect_width << ":" << config->aspect_height
567                 << "\n  Magnif:  " << config->magnification
568                 << std::endl;
569     }
570
571   int w,h;
572   float target_aspect = float(desktop_width) / desktop_height;
573   
574   if (config->aspect_width != 0 && config->aspect_height != 0)
575     target_aspect = float(config->aspect_width) / float(config->aspect_height);
576
577   float desktop_aspect = 4.0f / 3.0f; // random default fallback guess
578   
579   if (desktop_width != -1 && desktop_height != -1)
580     {
581       desktop_aspect = float(desktop_width) / float(desktop_height);
582     }
583
584   // Get the screen width
585   if (config->use_fullscreen)
586     {
587       w = config->fullscreen_width;
588       h = config->fullscreen_height;
589       desktop_aspect = float(w) / float(h);
590     }
591   else
592     {
593       w = config->window_width;        
594       h = config->window_height;
595     }
596
597   if (target_aspect > 1.0f)
598     {
599       SCREEN_WIDTH  = static_cast<int>(w * (target_aspect / desktop_aspect));
600       SCREEN_HEIGHT = static_cast<int>(h);
601     }
602   else
603     {
604       SCREEN_WIDTH  = static_cast<int>(w);
605       SCREEN_HEIGHT = static_cast<int>(h  * (target_aspect / desktop_aspect));
606     }
607
608   int max_width  = 1600; // FIXME: Maybe 1920 is ok too
609   int max_height = 1200;
610
611   if (config->magnification == 0.0f) // Magic value that means 'minfill'
612     {
613       // This scales SCREEN_WIDTH/SCREEN_HEIGHT so that they never excede
614       // max_width/max_height
615       if (SCREEN_WIDTH > max_width || SCREEN_HEIGHT > max_height)
616         {
617           float scale1  = float(max_width)/SCREEN_WIDTH;
618           float scale2  = float(max_height)/SCREEN_HEIGHT;
619           float scale   = (scale1 < scale2) ? scale1 : scale2;
620           SCREEN_WIDTH  = static_cast<int>(SCREEN_WIDTH  * scale);
621           SCREEN_HEIGHT = static_cast<int>(SCREEN_HEIGHT * scale);
622         }
623
624       glViewport(0, 0, w, h);
625     }
626   else
627     {
628       SCREEN_WIDTH  = static_cast<int>(SCREEN_WIDTH  / config->magnification);
629       SCREEN_HEIGHT = static_cast<int>(SCREEN_HEIGHT / config->magnification);
630
631       // This works by adding black borders around the screen to limit
632       // SCREEN_WIDTH/SCREEN_HEIGHT to max_width/max_height
633       int nw = w;
634       int nh = h;
635
636       if (SCREEN_WIDTH > max_width)
637         {
638           nw = static_cast<int>((float) nw * float(max_width)/SCREEN_WIDTH);
639           SCREEN_WIDTH = static_cast<int>(max_width);
640         }
641
642       if (SCREEN_HEIGHT > max_height)
643         {
644           nh = static_cast<int>((float) nh * float(max_height)/SCREEN_HEIGHT);
645           SCREEN_HEIGHT = static_cast<int>(max_height);
646         }
647
648       // Clear both buffers so that we get a clean black border without junk
649       glClear(GL_COLOR_BUFFER_BIT);
650       SDL_GL_SwapBuffers();
651       glClear(GL_COLOR_BUFFER_BIT);
652       SDL_GL_SwapBuffers();
653
654       if (0)
655         std::cout << (w-nw)/2 << " "
656                   << (h-nh)/2 << " "
657                   << nw << "x" << nh << std::endl;
658
659       glViewport(std::max(0, (w-nw)/2), 
660                  std::max(0, (h-nh)/2), 
661                  std::min(nw, w),
662                  std::min(nh, h));
663     }
664
665   if (0)
666     std::cout << "  -> " << SCREEN_WIDTH << "x" << SCREEN_HEIGHT << std::endl;
667
668   glMatrixMode(GL_PROJECTION);
669   glLoadIdentity();
670
671   glOrtho(0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, -1, 1);
672
673   glMatrixMode(GL_MODELVIEW);
674   glLoadIdentity();
675   glTranslatef(0, 0, 0);
676   check_gl_error("Setting up view matrices");
677 }
678
679 } // namespace GL
680
681 #endif