Implemented rounded rects with GL_TRIANGLE_STRIP
[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 #ifndef GP2X
155   //FIXME: This is not supported on the GP2X
156   if(config->try_vsync) {
157     /* we want vsync for smooth scrolling */
158     SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 1);
159   }
160 #endif
161
162   SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
163
164   // FIXME: Hu? 16bit rendering?
165   SDL_GL_SetAttribute(SDL_GL_RED_SIZE,   5);
166   SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
167   SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE,  5);
168
169   int flags = SDL_OPENGL;
170   int width;
171   int height;
172
173   if(config->use_fullscreen)
174     {
175       flags |= SDL_FULLSCREEN;
176       width  = config->fullscreen_width;
177       height = config->fullscreen_height;
178     }
179   else
180     {
181       flags |= SDL_RESIZABLE;
182       width  = config->window_width;
183       height = config->window_height;
184     }
185
186   int bpp = 0;
187   SDL_Surface *screen = SDL_SetVideoMode(width, height, bpp, flags);
188
189   if(screen == 0) {
190     std::stringstream msg;
191     msg << "Couldn't set video mode (" << width << "x" << height
192         << "-" << bpp << "bpp): " << SDL_GetError();
193     throw std::runtime_error(msg.str());
194   }
195
196   // setup opengl state and transform
197   glDisable(GL_DEPTH_TEST);
198   glDisable(GL_CULL_FACE);
199   glEnable(GL_TEXTURE_2D);
200   glEnable(GL_BLEND);
201   glEnableClientState(GL_VERTEX_ARRAY);
202   glEnableClientState(GL_TEXTURE_COORD_ARRAY);
203   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
204
205   // Init the projection matrix, viewport and stuff
206   apply_config();
207   
208   if(texture_manager == 0)
209     texture_manager = new TextureManager();
210   else
211     texture_manager->reload_textures();
212 }
213
214 Renderer::~Renderer()
215 {
216 }
217
218 void
219 Renderer::draw_surface(const DrawingRequest& request)
220 {
221   const Surface* surface = (const Surface*) request.request_data;
222   GL::Texture *gltexture = dynamic_cast<GL::Texture *>(surface->get_texture());
223   GL::SurfaceData *surface_data = reinterpret_cast<GL::SurfaceData *>(surface->get_surface_data());
224
225   glBindTexture(GL_TEXTURE_2D, gltexture->get_handle());
226   intern_draw(request.pos.x, request.pos.y,
227               request.pos.x + surface->get_width(),
228               request.pos.y + surface->get_height(),
229               surface_data->get_uv_left(),
230               surface_data->get_uv_top(),
231               surface_data->get_uv_right(),
232               surface_data->get_uv_bottom(),
233               request.angle,
234               request.alpha,
235               request.color,
236               request.blend,
237               request.drawing_effect);
238 }
239
240 void
241 Renderer::draw_surface_part(const DrawingRequest& request)
242 {
243   const SurfacePartRequest* surfacepartrequest
244     = (SurfacePartRequest*) request.request_data;
245   const Surface *surface = surfacepartrequest->surface;
246   GL::Texture *gltexture = dynamic_cast<GL::Texture *>(surface->get_texture());
247   GL::SurfaceData *surface_data = reinterpret_cast<GL::SurfaceData *>(surface->get_surface_data());
248
249   float uv_width = surface_data->get_uv_right() - surface_data->get_uv_left();
250   float uv_height = surface_data->get_uv_bottom() - surface_data->get_uv_top();
251
252   float uv_left = surface_data->get_uv_left() + (uv_width * surfacepartrequest->source.x) / surface->get_width();
253   float uv_top = surface_data->get_uv_top() + (uv_height * surfacepartrequest->source.y) / surface->get_height();
254   float uv_right = surface_data->get_uv_left() + (uv_width * (surfacepartrequest->source.x + surfacepartrequest->size.x)) / surface->get_width();
255   float uv_bottom = surface_data->get_uv_top() + (uv_height * (surfacepartrequest->source.y + surfacepartrequest->size.y)) / surface->get_height();
256
257   glBindTexture(GL_TEXTURE_2D, gltexture->get_handle());
258   intern_draw(request.pos.x, request.pos.y,
259               request.pos.x + surfacepartrequest->size.x,
260               request.pos.y + surfacepartrequest->size.y,
261               uv_left,
262               uv_top,
263               uv_right,
264               uv_bottom,
265               0.0,
266               request.alpha,
267               Color(1.0, 1.0, 1.0),
268               Blend(),
269               request.drawing_effect);
270 }
271
272 void
273 Renderer::draw_gradient(const DrawingRequest& request)
274 {
275   const GradientRequest* gradientrequest 
276     = (GradientRequest*) request.request_data;
277   const Color& top = gradientrequest->top;
278   const Color& bottom = gradientrequest->bottom;
279
280   glDisable(GL_TEXTURE_2D);
281   glDisableClientState(GL_TEXTURE_COORD_ARRAY);
282   glEnableClientState(GL_COLOR_ARRAY);
283
284   float vertices[] = {
285     0, 0,
286     SCREEN_WIDTH, 0,
287     SCREEN_WIDTH, SCREEN_HEIGHT,
288     0, SCREEN_HEIGHT
289   };
290   glVertexPointer(2, GL_FLOAT, 0, vertices);
291
292   float colors[] = {
293     top.red, top.green, top.blue, top.alpha,
294     top.red, top.green, top.blue, top.alpha,
295     bottom.red, bottom.green, bottom.blue, bottom.alpha,
296     bottom.red, bottom.green, bottom.blue, bottom.alpha,
297   };
298   glColorPointer(4, GL_FLOAT, 0, colors);
299
300   glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
301
302   glDisableClientState(GL_COLOR_ARRAY);
303   glEnableClientState(GL_TEXTURE_COORD_ARRAY);
304
305   glEnable(GL_TEXTURE_2D);
306   glColor4f(1, 1, 1, 1);
307 }
308
309 void
310 Renderer::draw_filled_rect(const DrawingRequest& request)
311 {
312   const FillRectRequest* fillrectrequest
313     = (FillRectRequest*) request.request_data;
314
315   glDisable(GL_TEXTURE_2D);
316   glColor4f(fillrectrequest->color.red, fillrectrequest->color.green,
317             fillrectrequest->color.blue, fillrectrequest->color.alpha);
318   glDisableClientState(GL_TEXTURE_COORD_ARRAY);
319   
320   if (fillrectrequest->radius != 0.0f)
321     {
322       // draw round rect
323       // Keep radius in the limits, so that we get a circle instead of
324       // just graphic junk
325       float radius = std::min(fillrectrequest->radius,
326                               std::min(fillrectrequest->size.x/2,
327                                        fillrectrequest->size.y/2));
328
329       // inner rectangle
330       Rect irect(request.pos.x    + radius,
331                  request.pos.y    + radius,
332                  request.pos.x + fillrectrequest->size.x - radius,
333                  request.pos.y + fillrectrequest->size.y - radius);
334
335
336       int n = 8;
337       int p = 0;
338       float vertices[(n+1) * 4 * 2];
339
340       for(int i = 0; i <= n; ++i)
341         {
342           float x = sinf(i * (M_PI/2) / n) * radius;
343           float y = cosf(i * (M_PI/2) / n) * radius;
344
345           vertices[p++] = irect.get_left() - x;
346           vertices[p++] = irect.get_top()  - y;
347
348           vertices[p++] = irect.get_right() + x;
349           vertices[p++] = irect.get_top()   - y;
350         }
351
352       for(int i = 0; i <= n; ++i)
353         {
354           float x = cosf(i * (M_PI/2) / n) * radius;
355           float y = sinf(i * (M_PI/2) / n) * radius;
356
357           vertices[p++] = irect.get_left()   - x;
358           vertices[p++] = irect.get_bottom() + y;
359
360           vertices[p++] = irect.get_right()  + x;
361           vertices[p++] = irect.get_bottom() + y;
362         }
363
364       glVertexPointer(2, GL_FLOAT, 0, vertices);
365       glDrawArrays(GL_TRIANGLE_STRIP, 0,  sizeof(vertices)/sizeof(float)/2);
366     }
367   else
368     {
369       float x = request.pos.x;
370       float y = request.pos.y;
371       float w = fillrectrequest->size.x;
372       float h = fillrectrequest->size.y;
373
374       float vertices[] = {
375         x,   y,
376         x+w, y,
377         x+w, y+h,
378         x,   y+h
379       };
380       glVertexPointer(2, GL_FLOAT, 0, vertices);
381
382       glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
383     }
384
385   glEnableClientState(GL_TEXTURE_COORD_ARRAY);
386   glEnable(GL_TEXTURE_2D);
387   glColor4f(1, 1, 1, 1);
388 }
389
390 void
391 Renderer::draw_inverse_ellipse(const DrawingRequest& request)
392 {
393   const InverseEllipseRequest* ellipse = (InverseEllipseRequest*)request.request_data;
394
395   glDisable(GL_TEXTURE_2D);
396   glColor4f(ellipse->color.red,  ellipse->color.green,
397             ellipse->color.blue, ellipse->color.alpha);
398     
399   float x = request.pos.x;
400   float y = request.pos.y;
401   float w = ellipse->size.x/2.0f;
402   float h = ellipse->size.y/2.0f;
403
404   static const int slices = 16;
405   static const int points = (slices+1) * 12;
406
407   float vertices[points * 2];
408   int   p = 0;
409
410   // Bottom
411   vertices[p++] = SCREEN_WIDTH; vertices[p++] = SCREEN_HEIGHT;
412   vertices[p++] = 0;            vertices[p++] = SCREEN_HEIGHT;
413   vertices[p++] = x;            vertices[p++] = y+h;
414
415   // Top
416   vertices[p++] = SCREEN_WIDTH; vertices[p++] = 0;
417   vertices[p++] = 0;            vertices[p++] = 0;
418   vertices[p++] = x;            vertices[p++] = y-h;
419
420   // Left
421   vertices[p++] = SCREEN_WIDTH; vertices[p++] = 0;
422   vertices[p++] = SCREEN_WIDTH; vertices[p++] = SCREEN_HEIGHT;
423   vertices[p++] = x+w;          vertices[p++] = y;
424
425   // Right
426   vertices[p++] = 0;            vertices[p++] = 0;
427   vertices[p++] = 0;            vertices[p++] = SCREEN_HEIGHT;
428   vertices[p++] = x-w;          vertices[p++] = y;
429
430   for(int i = 0; i < slices; ++i)
431     {
432       float ex1 = sinf(M_PI/2 / slices * i) * w;
433       float ey1 = cosf(M_PI/2 / slices * i) * h;
434
435       float ex2 = sinf(M_PI/2 / slices * (i+1)) * w;
436       float ey2 = cosf(M_PI/2 / slices * (i+1)) * h;
437
438       // Bottom/Right
439       vertices[p++] = SCREEN_WIDTH; vertices[p++] = SCREEN_HEIGHT;
440       vertices[p++] = x + ex1;      vertices[p++] = y + ey1;
441       vertices[p++] = x + ex2;      vertices[p++] = y + ey2;
442
443       // Top/Left
444       vertices[p++] = 0;            vertices[p++] = 0;
445       vertices[p++] = x - ex1;      vertices[p++] = y - ey1;
446       vertices[p++] = x - ex2;      vertices[p++] = y - ey2;
447
448       // Top/Right
449       vertices[p++] = SCREEN_WIDTH; vertices[p++] = 0;
450       vertices[p++] = x + ex1;      vertices[p++] = y - ey1;
451       vertices[p++] = x + ex2;      vertices[p++] = y - ey2;
452
453       // Bottom/Left
454       vertices[p++] = 0;            vertices[p++] = SCREEN_HEIGHT;
455       vertices[p++] = x - ex1;      vertices[p++] = y + ey1;
456       vertices[p++] = x - ex2;      vertices[p++] = y + ey2;
457     }
458
459   glDisableClientState(GL_TEXTURE_COORD_ARRAY);
460   glVertexPointer(2, GL_FLOAT, 0, vertices);
461
462   glDrawArrays(GL_TRIANGLES, 0, points);
463
464   glEnableClientState(GL_TEXTURE_COORD_ARRAY);
465
466   glEnable(GL_TEXTURE_2D);
467   glColor4f(1, 1, 1, 1);    
468 }
469
470 void 
471 Renderer::do_take_screenshot()
472 {
473   // [Christoph] TODO: Yes, this method also takes care of the actual disk I/O. Split it?
474
475   SDL_Surface *shot_surf;
476   // create surface to hold screenshot
477 #if SDL_BYTEORDER == SDL_BIG_ENDIAN
478   shot_surf = SDL_CreateRGBSurface(SDL_SWSURFACE, SCREEN_WIDTH, SCREEN_HEIGHT, 24, 0x00FF0000, 0x0000FF00, 0x000000FF, 0);
479 #else
480   shot_surf = SDL_CreateRGBSurface(SDL_SWSURFACE, SCREEN_WIDTH, SCREEN_HEIGHT, 24, 0x000000FF, 0x0000FF00, 0x00FF0000, 0);
481 #endif
482   if (!shot_surf) {
483     log_warning << "Could not create RGB Surface to contain screenshot" << std::endl;
484     return;
485   }
486
487   // read pixels into array
488   char* pixels = new char[3 * SCREEN_WIDTH * SCREEN_HEIGHT];
489   if (!pixels) {
490     log_warning << "Could not allocate memory to store screenshot" << std::endl;
491     SDL_FreeSurface(shot_surf);
492     return;
493   }
494   glReadPixels(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, GL_RGB, GL_UNSIGNED_BYTE, pixels);
495
496   // copy array line-by-line
497   for (int i = 0; i < SCREEN_HEIGHT; i++) {
498     char* src = pixels + (3 * SCREEN_WIDTH * (SCREEN_HEIGHT - i - 1));
499     if(SDL_MUSTLOCK(shot_surf))
500       {
501         SDL_LockSurface(shot_surf);
502       }
503     char* dst = ((char*)shot_surf->pixels) + i * shot_surf->pitch;
504     memcpy(dst, src, 3 * SCREEN_WIDTH);
505     if(SDL_MUSTLOCK(shot_surf))
506       {
507         SDL_UnlockSurface(shot_surf);
508       }
509   }
510
511   // free array
512   delete[](pixels);
513
514   // save screenshot
515   static const std::string writeDir = PHYSFS_getWriteDir();
516   static const std::string dirSep = PHYSFS_getDirSeparator();
517   static const std::string baseName = "screenshot";
518   static const std::string fileExt = ".bmp";
519   std::string fullFilename;
520   for (int num = 0; num < 1000; num++) {
521     std::ostringstream oss;
522     oss << baseName;
523     oss << std::setw(3) << std::setfill('0') << num;
524     oss << fileExt;
525     std::string fileName = oss.str();
526     fullFilename = writeDir + dirSep + fileName;
527     if (!PHYSFS_exists(fileName.c_str())) {
528       SDL_SaveBMP(shot_surf, fullFilename.c_str());
529       log_debug << "Wrote screenshot to \"" << fullFilename << "\"" << std::endl;
530       SDL_FreeSurface(shot_surf);
531       return;
532     }
533   }
534   log_warning << "Did not save screenshot, because all files up to \"" << fullFilename << "\" already existed" << std::endl;
535   SDL_FreeSurface(shot_surf);
536 }
537
538 void
539 Renderer::flip()
540 {
541   assert_gl("drawing");
542   SDL_GL_SwapBuffers();
543 }
544
545 void
546 Renderer::resize(int w, int h)
547 {
548   // This causes the screen to go black, which is annoying, but seems
549   // unavoidable with SDL at the moment
550   SDL_SetVideoMode(w, h, 0, SDL_OPENGL | SDL_RESIZABLE);
551
552   config->window_width  = w;
553   config->window_height = h;
554
555   apply_config();
556 }
557
558 void
559 Renderer::apply_config()
560 {    
561   if (0)
562     {
563       std::cout << "Applying Config:" 
564                 << "\n  Desktop: " << desktop_width << "x" << desktop_height
565                 << "\n  Window:  " << config->window_width << "x" << config->window_height
566                 << "\n  FullRes: " << config->fullscreen_width << "x" << config->fullscreen_height
567                 << "\n  Aspect:  " << config->aspect_width << ":" << config->aspect_height
568                 << "\n  Magnif:  " << config->magnification
569                 << std::endl;
570     }
571
572   int w,h;
573   float target_aspect = float(desktop_width) / desktop_height;
574   
575   if (config->aspect_width != 0 && config->aspect_height != 0)
576     target_aspect = float(config->aspect_width) / float(config->aspect_height);
577
578   float desktop_aspect = 4.0f / 3.0f; // random default fallback guess
579   
580   if (desktop_width != -1 && desktop_height != -1)
581     {
582       desktop_aspect = float(desktop_width) / float(desktop_height);
583     }
584
585   // Get the screen width
586   if (config->use_fullscreen)
587     {
588       w = config->fullscreen_width;
589       h = config->fullscreen_height;
590       desktop_aspect = float(w) / float(h);
591     }
592   else
593     {
594       w = config->window_width;        
595       h = config->window_height;
596     }
597
598   if (target_aspect > 1.0f)
599     {
600       SCREEN_WIDTH  = static_cast<int>(w * (target_aspect / desktop_aspect));
601       SCREEN_HEIGHT = static_cast<int>(h);
602     }
603   else
604     {
605       SCREEN_WIDTH  = static_cast<int>(w);
606       SCREEN_HEIGHT = static_cast<int>(h  * (target_aspect / desktop_aspect));
607     }
608
609   int max_width  = 1600; // FIXME: Maybe 1920 is ok too
610   int max_height = 1200;
611
612   if (config->magnification == 0.0f) // Magic value that means 'minfill'
613     {
614       // This scales SCREEN_WIDTH/SCREEN_HEIGHT so that they never excede
615       // max_width/max_height
616       if (SCREEN_WIDTH > max_width || SCREEN_HEIGHT > max_height)
617         {
618           float scale1  = float(max_width)/SCREEN_WIDTH;
619           float scale2  = float(max_height)/SCREEN_HEIGHT;
620           float scale   = (scale1 < scale2) ? scale1 : scale2;
621           SCREEN_WIDTH  = static_cast<int>(SCREEN_WIDTH  * scale);
622           SCREEN_HEIGHT = static_cast<int>(SCREEN_HEIGHT * scale);
623         }
624
625       glViewport(0, 0, w, h);
626     }
627   else
628     {
629       SCREEN_WIDTH  = static_cast<int>(SCREEN_WIDTH  / config->magnification);
630       SCREEN_HEIGHT = static_cast<int>(SCREEN_HEIGHT / config->magnification);
631
632       // This works by adding black borders around the screen to limit
633       // SCREEN_WIDTH/SCREEN_HEIGHT to max_width/max_height
634       int nw = w;
635       int nh = h;
636
637       if (SCREEN_WIDTH > max_width)
638         {
639           nw = static_cast<int>((float) nw * float(max_width)/SCREEN_WIDTH);
640           SCREEN_WIDTH = static_cast<int>(max_width);
641         }
642
643       if (SCREEN_HEIGHT > max_height)
644         {
645           nh = static_cast<int>((float) nh * float(max_height)/SCREEN_HEIGHT);
646           SCREEN_HEIGHT = static_cast<int>(max_height);
647         }
648
649       // Clear both buffers so that we get a clean black border without junk
650       glClear(GL_COLOR_BUFFER_BIT);
651       SDL_GL_SwapBuffers();
652       glClear(GL_COLOR_BUFFER_BIT);
653       SDL_GL_SwapBuffers();
654
655       if (0)
656         std::cout << (w-nw)/2 << " "
657                   << (h-nh)/2 << " "
658                   << nw << "x" << nh << std::endl;
659
660       glViewport(std::max(0, (w-nw)/2), 
661                  std::max(0, (h-nh)/2), 
662                  std::min(nw, w),
663                  std::min(nh, h));
664     }
665
666   if (0)
667     std::cout << "  -> " << SCREEN_WIDTH << "x" << SCREEN_HEIGHT << std::endl;
668
669   glMatrixMode(GL_PROJECTION);
670   glLoadIdentity();
671
672   glOrtho(0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, -1, 1);
673
674   glMatrixMode(GL_MODELVIEW);
675   glLoadIdentity();
676   glTranslatef(0, 0, 0);
677   check_gl_error("Setting up view matrices");
678 }
679
680 } // namespace GL
681
682 #endif