Some more messing around with aspect-ratio, window resize and stuff
[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 namespace 
49 {
50 inline void intern_draw(float left, float top, float right, float bottom,
51                         float uv_left, float uv_top,
52                         float uv_right, float uv_bottom,
53                         float angle, float alpha,
54                         const Color& color,
55                         const Blend& blend,
56                         DrawingEffect effect)
57 {
58   if(effect & HORIZONTAL_FLIP)
59     std::swap(uv_left, uv_right);
60  
61   if(effect & VERTICAL_FLIP) 
62     std::swap(uv_top, uv_bottom);
63  
64   if (angle == 0.0f)
65     { // unrotated blit
66       glBlendFunc(blend.sfactor, blend.dfactor);
67       glColor4f(color.red, color.green, color.blue, color.alpha * alpha);
68       glBegin(GL_QUADS);
69       glTexCoord2f(uv_left, uv_top);
70       glVertex2f(left, top);
71
72       glTexCoord2f(uv_right, uv_top);
73       glVertex2f(right, top);
74
75       glTexCoord2f(uv_right, uv_bottom);
76       glVertex2f(right, bottom);
77
78       glTexCoord2f(uv_left, uv_bottom);
79       glVertex2f(left, bottom);
80       glEnd();
81     }
82   else
83     { // rotated blit
84       float center_x = (left + right) / 2;
85       float center_y = (top + bottom) / 2;
86
87       float sa = sinf(angle/180.0f*M_PI);
88       float ca = cosf(angle/180.0f*M_PI);
89
90       left  -= center_x;
91       right -= center_x;
92
93       top    -= center_y;
94       bottom -= center_y;
95
96       glBlendFunc(blend.sfactor, blend.dfactor);
97       glColor4f(color.red, color.green, color.blue, color.alpha * alpha);
98       glBegin(GL_QUADS);
99       glTexCoord2f(uv_left, uv_top);
100       glVertex2f(left*ca - top*sa + center_x,
101                  left*sa + top*ca + center_y);
102
103       glTexCoord2f(uv_right, uv_top);
104       glVertex2f(right*ca - top*sa + center_x,
105                  right*sa + top*ca + center_y);
106
107       glTexCoord2f(uv_right, uv_bottom);
108       glVertex2f(right*ca - bottom*sa + center_x,
109                  right*sa + bottom*ca + center_y);
110
111       glTexCoord2f(uv_left, uv_bottom);
112       glVertex2f(left*ca - bottom*sa + center_x,
113                  left*sa + bottom*ca + center_y);
114       glEnd();
115     }
116
117   // FIXME: find a better way to restore the blend mode
118   glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
119   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
120 }
121 }
122
123 namespace GL {
124
125 Renderer::Renderer()
126   : desktop_width(-1),
127     desktop_height(-1)
128 {
129   ::Renderer::instance_ = this;
130
131 #if SDL_MAJOR_VERSION > 1 || SDL_MINOR_VERSION > 2 || (SDL_MINOR_VERSION == 2 && SDL_PATCHLEVEL >= 10)
132   // unfortunately only newer SDLs have these infos.
133   // This must be called before SDL_SetVideoMode() or it will return
134   // the window size instead of the desktop size.
135   const SDL_VideoInfo *info = SDL_GetVideoInfo();
136   if (info)
137     {
138       desktop_width  = info->current_w;
139       desktop_height = info->current_h;     
140     }
141 #endif
142
143   if(texture_manager != 0)
144     texture_manager->save_textures();
145
146   if(config->try_vsync) {
147     /* we want vsync for smooth scrolling */
148     SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 1);
149   }
150
151   SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
152
153   // Hu? 16bit rendering?
154   SDL_GL_SetAttribute(SDL_GL_RED_SIZE,   5);
155   SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
156   SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE,  5);
157
158   int flags = SDL_OPENGL;
159   int width;
160   int height;
161   if(config->use_fullscreen)
162     {
163       flags |= SDL_FULLSCREEN;
164       width  = config->fullscreen_width;
165       height = config->fullscreen_height;
166     }
167   else
168     {
169       flags |= SDL_RESIZABLE;
170       width  = config->window_width;
171       height = config->window_height;
172     }
173   int bpp = 0;
174
175   SDL_Surface *screen = SDL_SetVideoMode(width, height, bpp, flags);
176   if(screen == 0) {
177     std::stringstream msg;
178     msg << "Couldn't set video mode (" << width << "x" << height
179         << "-" << bpp << "bpp): " << SDL_GetError();
180     throw std::runtime_error(msg.str());
181   }
182
183   // setup opengl state and transform
184   glDisable(GL_DEPTH_TEST);
185   glDisable(GL_CULL_FACE);
186   glEnable(GL_TEXTURE_2D);
187   glEnable(GL_BLEND);
188   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
189
190   glViewport(0, 0, screen->w, screen->h);
191   glMatrixMode(GL_PROJECTION);
192   glLoadIdentity();
193
194   // logical resolution here not real monitor resolution
195   glOrtho(0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, -1.0, 1.0);
196
197   glMatrixMode(GL_MODELVIEW);
198   glLoadIdentity();
199   glTranslatef(0, 0, 0);
200
201   check_gl_error("Setting up view matrices");
202
203
204   if(texture_manager == 0)
205     texture_manager = new TextureManager();
206   else
207     texture_manager->reload_textures();
208 }
209
210 Renderer::~Renderer()
211 {
212 }
213
214 void
215 Renderer::draw_surface(const DrawingRequest& request)
216 {
217   const Surface* surface = (const Surface*) request.request_data;
218   GL::Texture *gltexture = dynamic_cast<GL::Texture *>(surface->get_texture());
219   GL::SurfaceData *surface_data = reinterpret_cast<GL::SurfaceData *>(surface->get_surface_data());
220
221   glBindTexture(GL_TEXTURE_2D, gltexture->get_handle());
222   intern_draw(request.pos.x, request.pos.y,
223               request.pos.x + surface->get_width(),
224               request.pos.y + surface->get_height(),
225               surface_data->get_uv_left(),
226               surface_data->get_uv_top(),
227               surface_data->get_uv_right(),
228               surface_data->get_uv_bottom(),
229               request.angle,
230               request.alpha,
231               request.color,
232               request.blend,
233               request.drawing_effect);
234 }
235
236 void
237 Renderer::draw_surface_part(const DrawingRequest& request)
238 {
239   const SurfacePartRequest* surfacepartrequest
240     = (SurfacePartRequest*) request.request_data;
241   const Surface *surface = surfacepartrequest->surface;
242   GL::Texture *gltexture = dynamic_cast<GL::Texture *>(surface->get_texture());
243   GL::SurfaceData *surface_data = reinterpret_cast<GL::SurfaceData *>(surface->get_surface_data());
244
245   float uv_width = surface_data->get_uv_right() - surface_data->get_uv_left();
246   float uv_height = surface_data->get_uv_bottom() - surface_data->get_uv_top();
247
248   float uv_left = surface_data->get_uv_left() + (uv_width * surfacepartrequest->source.x) / surface->get_width();
249   float uv_top = surface_data->get_uv_top() + (uv_height * surfacepartrequest->source.y) / surface->get_height();
250   float uv_right = surface_data->get_uv_left() + (uv_width * (surfacepartrequest->source.x + surfacepartrequest->size.x)) / surface->get_width();
251   float uv_bottom = surface_data->get_uv_top() + (uv_height * (surfacepartrequest->source.y + surfacepartrequest->size.y)) / surface->get_height();
252
253   glBindTexture(GL_TEXTURE_2D, gltexture->get_handle());
254   intern_draw(request.pos.x, request.pos.y,
255               request.pos.x + surfacepartrequest->size.x,
256               request.pos.y + surfacepartrequest->size.y,
257               uv_left,
258               uv_top,
259               uv_right,
260               uv_bottom,
261               0.0,
262               request.alpha,
263               Color(1.0, 1.0, 1.0),
264               Blend(),
265               request.drawing_effect);
266 }
267
268 void
269 Renderer::draw_gradient(const DrawingRequest& request)
270 {
271   const GradientRequest* gradientrequest 
272     = (GradientRequest*) request.request_data;
273   const Color& top = gradientrequest->top;
274   const Color& bottom = gradientrequest->bottom;
275
276   glDisable(GL_TEXTURE_2D);
277   glBegin(GL_QUADS);
278   glColor4f(top.red, top.green, top.blue, top.alpha);
279   glVertex2f(0, 0);
280   glVertex2f(SCREEN_WIDTH, 0);
281   glColor4f(bottom.red, bottom.green, bottom.blue, bottom.alpha);
282   glVertex2f(SCREEN_WIDTH, SCREEN_HEIGHT);
283   glVertex2f(0, SCREEN_HEIGHT);
284   glEnd();
285   glEnable(GL_TEXTURE_2D);
286   glColor4f(1, 1, 1, 1);
287 }
288
289 void
290 Renderer::draw_filled_rect(const DrawingRequest& request)
291 {
292   const FillRectRequest* fillrectrequest
293     = (FillRectRequest*) request.request_data;
294
295   if (fillrectrequest->radius != 0.0f)
296     {
297       // draw round rect
298       // Keep radius in the limits, so that we get a circle instead of
299       // just graphic junk
300       float radius = std::min(fillrectrequest->radius,
301                               std::min(fillrectrequest->size.x/2,
302                                        fillrectrequest->size.y/2));
303
304       // inner rectangle
305       Rect irect(request.pos.x    + radius,
306                  request.pos.y    + radius,
307                  request.pos.x + fillrectrequest->size.x - radius,
308                  request.pos.y + fillrectrequest->size.y - radius);
309
310       glDisable(GL_TEXTURE_2D);
311       glColor4f(fillrectrequest->color.red, fillrectrequest->color.green,
312                 fillrectrequest->color.blue, fillrectrequest->color.alpha);
313
314
315       int n = 8;
316       glBegin(GL_QUAD_STRIP);
317       for(int i = 0; i <= n; ++i)
318         {
319           float x = sinf(i * (M_PI/2) / n) * radius;
320           float y = cosf(i * (M_PI/2) / n) * radius;
321
322           glVertex2f(irect.get_left()  - x, irect.get_top() - y);
323           glVertex2f(irect.get_right() + x, irect.get_top() - y);
324         }
325       for(int i = 0; i <= n; ++i)
326         {
327           float x = cosf(i * (M_PI/2) / n) * radius;
328           float y = sinf(i * (M_PI/2) / n) * radius;
329
330           glVertex2f(irect.get_left()  - x, irect.get_bottom() + y);
331           glVertex2f(irect.get_right() + x, irect.get_bottom() + y);
332         }
333       glEnd();
334       glEnable(GL_TEXTURE_2D);
335       glColor4f(1, 1, 1, 1);
336     }
337   else
338     {
339       float x = request.pos.x;
340       float y = request.pos.y;
341       float w = fillrectrequest->size.x;
342       float h = fillrectrequest->size.y;
343
344       glDisable(GL_TEXTURE_2D);
345       glColor4f(fillrectrequest->color.red, fillrectrequest->color.green,
346                 fillrectrequest->color.blue, fillrectrequest->color.alpha);
347
348       glBegin(GL_QUADS);
349       glVertex2f(x, y);
350       glVertex2f(x+w, y);
351       glVertex2f(x+w, y+h);
352       glVertex2f(x, y+h);
353       glEnd();
354       glEnable(GL_TEXTURE_2D);
355       glColor4f(1, 1, 1, 1);
356     }
357 }
358
359 void
360 Renderer::draw_inverse_ellipse(const DrawingRequest& request)
361 {
362   const InverseEllipseRequest* ellipse = (InverseEllipseRequest*)request.request_data;
363
364   glDisable(GL_TEXTURE_2D);
365   glColor4f(ellipse->color.red,  ellipse->color.green,
366             ellipse->color.blue, ellipse->color.alpha);
367     
368   float x = request.pos.x;
369   float y = request.pos.y;
370   float w = ellipse->size.x/2.0f;
371   float h = ellipse->size.y/2.0f;
372
373   glBegin(GL_TRIANGLES);
374     
375   // Bottom
376   glVertex2f(SCREEN_WIDTH, SCREEN_HEIGHT);
377   glVertex2f(0, SCREEN_HEIGHT);
378   glVertex2f(x, y+h);
379
380   // Top
381   glVertex2f(SCREEN_WIDTH, 0);
382   glVertex2f(0, 0);
383   glVertex2f(x, y-h);
384
385   // Left
386   glVertex2f(SCREEN_WIDTH, 0);
387   glVertex2f(SCREEN_WIDTH, SCREEN_HEIGHT);
388   glVertex2f(x+w, y);
389
390   // Right
391   glVertex2f(0, 0);
392   glVertex2f(0, SCREEN_HEIGHT);
393   glVertex2f(x-w, y);
394
395   glEnd();
396         
397   int slices = 16;
398   for(int i = 0; i < slices; ++i)
399     {
400       float ex1 = sinf(M_PI/2 / slices * i) * w;
401       float ey1 = cosf(M_PI/2 / slices * i) * h;
402
403       float ex2 = sinf(M_PI/2 / slices * (i+1)) * w;
404       float ey2 = cosf(M_PI/2 / slices * (i+1)) * h;
405
406       glBegin(GL_TRIANGLES);
407
408       // Bottom/Right
409       glVertex2f(SCREEN_WIDTH, SCREEN_HEIGHT);
410       glVertex2f(x + ex1, y + ey1);
411       glVertex2f(x + ex2, y + ey2);
412
413       // Top/Left
414       glVertex2f(0, 0);
415       glVertex2f(x - ex1, y - ey1);
416       glVertex2f(x - ex2, y - ey2);
417
418       // Top/Right
419       glVertex2f(SCREEN_WIDTH, 0);
420       glVertex2f(x + ex1, y - ey1);
421       glVertex2f(x + ex2, y - ey2);
422
423       // Bottom/Left
424       glVertex2f(0, SCREEN_HEIGHT);
425       glVertex2f(x - ex1, y + ey1);
426       glVertex2f(x - ex2, y + ey2);
427
428       glEnd();
429     }
430   glEnable(GL_TEXTURE_2D);
431   glColor4f(1, 1, 1, 1);    
432 }
433
434 void 
435 Renderer::do_take_screenshot()
436 {
437   // [Christoph] TODO: Yes, this method also takes care of the actual disk I/O. Split it?
438
439   SDL_Surface *shot_surf;
440   // create surface to hold screenshot
441 #if SDL_BYTEORDER == SDL_BIG_ENDIAN
442   shot_surf = SDL_CreateRGBSurface(SDL_SWSURFACE, SCREEN_WIDTH, SCREEN_HEIGHT, 24, 0x00FF0000, 0x0000FF00, 0x000000FF, 0);
443 #else
444   shot_surf = SDL_CreateRGBSurface(SDL_SWSURFACE, SCREEN_WIDTH, SCREEN_HEIGHT, 24, 0x000000FF, 0x0000FF00, 0x00FF0000, 0);
445 #endif
446   if (!shot_surf) {
447     log_warning << "Could not create RGB Surface to contain screenshot" << std::endl;
448     return;
449   }
450
451   // read pixels into array
452   char* pixels = new char[3 * SCREEN_WIDTH * SCREEN_HEIGHT];
453   if (!pixels) {
454     log_warning << "Could not allocate memory to store screenshot" << std::endl;
455     SDL_FreeSurface(shot_surf);
456     return;
457   }
458   glReadPixels(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, GL_RGB, GL_UNSIGNED_BYTE, pixels);
459
460   // copy array line-by-line
461   for (int i = 0; i < SCREEN_HEIGHT; i++) {
462     char* src = pixels + (3 * SCREEN_WIDTH * (SCREEN_HEIGHT - i - 1));
463     if(SDL_MUSTLOCK(shot_surf))
464       {
465         SDL_LockSurface(shot_surf);
466       }
467     char* dst = ((char*)shot_surf->pixels) + i * shot_surf->pitch;
468     memcpy(dst, src, 3 * SCREEN_WIDTH);
469     if(SDL_MUSTLOCK(shot_surf))
470       {
471         SDL_UnlockSurface(shot_surf);
472       }
473   }
474
475   // free array
476   delete[](pixels);
477
478   // save screenshot
479   static const std::string writeDir = PHYSFS_getWriteDir();
480   static const std::string dirSep = PHYSFS_getDirSeparator();
481   static const std::string baseName = "screenshot";
482   static const std::string fileExt = ".bmp";
483   std::string fullFilename;
484   for (int num = 0; num < 1000; num++) {
485     std::ostringstream oss;
486     oss << baseName;
487     oss << std::setw(3) << std::setfill('0') << num;
488     oss << fileExt;
489     std::string fileName = oss.str();
490     fullFilename = writeDir + dirSep + fileName;
491     if (!PHYSFS_exists(fileName.c_str())) {
492       SDL_SaveBMP(shot_surf, fullFilename.c_str());
493       log_debug << "Wrote screenshot to \"" << fullFilename << "\"" << std::endl;
494       SDL_FreeSurface(shot_surf);
495       return;
496     }
497   }
498   log_warning << "Did not save screenshot, because all files up to \"" << fullFilename << "\" already existed" << std::endl;
499   SDL_FreeSurface(shot_surf);
500 }
501
502 void
503 Renderer::flip()
504 {
505   assert_gl("drawing");
506   SDL_GL_SwapBuffers();
507 }
508
509 void
510 Renderer::resize(int w, int h)
511 {
512   SDL_SetVideoMode(w, h, 0, SDL_OPENGL | SDL_RESIZABLE);
513
514   config->window_width  = w;
515   config->window_height = h;
516
517   apply_config();
518 }
519
520 void
521 Renderer::apply_config()
522 {    
523   std::cout << "Applying Config:" 
524             << "\n  Desktop: " << desktop_width << "x" << desktop_height
525             << "\n  Window:  " << config->window_width << "x" << config->window_height
526             << "\n  FullRes: " << config->fullscreen_width << "x" << config->fullscreen_height
527             << "\n  Aspect:  " << config->aspect_width << ":" << config->aspect_height
528             << "\n  Magnif:  " << config->magnification
529             << std::endl;
530
531   int w,h;
532   float target_aspect  = float(config->aspect_width) / float(config->aspect_height);
533   float desktop_aspect = 4.0f / 3.0f; // random default fallback guess
534   
535   if (desktop_width != -1 && desktop_height != -1)
536     {
537       desktop_aspect = float(desktop_width) / float(desktop_height);
538     }
539
540   if (config->use_fullscreen)
541     {
542       w = config->fullscreen_width;
543       h = config->fullscreen_height;
544       desktop_aspect = float(w) / float(h);
545     }
546   else
547     {
548       w = config->window_width;        
549       h = config->window_height;
550     }
551
552   if (target_aspect > 1.0f)
553     {
554       SCREEN_WIDTH  = w * (target_aspect / desktop_aspect);
555       SCREEN_HEIGHT = h;
556     }
557   else
558     {
559       SCREEN_WIDTH  = w;
560       SCREEN_HEIGHT = h  * (target_aspect / desktop_aspect);
561     }
562
563   SCREEN_WIDTH  *= config->magnification;  
564   SCREEN_HEIGHT *= config->magnification;  
565
566   int max_width  = 1600;
567   int max_height = 1200;
568   
569   // A little wonky
570   if (SCREEN_WIDTH > max_width)
571     {
572       float scale = float(max_width)/SCREEN_WIDTH;
573       SCREEN_WIDTH  *= scale;
574       SCREEN_HEIGHT *= scale;
575     }
576   else if (SCREEN_HEIGHT > max_height)
577     {
578       float scale = float(max_height)/SCREEN_HEIGHT;
579       SCREEN_WIDTH  *= scale;
580       SCREEN_HEIGHT *= scale;
581     }
582   
583   std::cout << " -> " << SCREEN_WIDTH << "x" << SCREEN_HEIGHT << std::endl;
584
585   glViewport(0, 0, w, h);
586
587   glMatrixMode(GL_PROJECTION);
588   glLoadIdentity();
589   glOrtho(0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, -1.0, 1.0);    
590 }
591
592 } // namespace GL
593
594 #endif