Added experimental and unfinished window resize more fixes will follow later, might...
[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   {
127     ::Renderer::instance_ = this;
128
129     if(texture_manager != 0)
130       texture_manager->save_textures();
131
132     if(config->try_vsync) {
133       /* we want vsync for smooth scrolling */
134     SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 1);
135     }
136
137     SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
138
139     // Hu? 16bit rendering?
140     SDL_GL_SetAttribute(SDL_GL_RED_SIZE,   5);
141     SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
142     SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE,  5);
143
144     int flags = SDL_OPENGL;
145     int width;
146     int height;
147     if(config->use_fullscreen)
148       {
149         flags |= SDL_FULLSCREEN;
150         width  = config->fullscreen_width;
151         height = config->fullscreen_height;
152       }
153     else
154       {
155         flags |= SDL_RESIZABLE;
156         width  = config->window_width;
157         height = config->window_height;
158       }
159     int bpp = 0;
160
161     SDL_Surface *screen = SDL_SetVideoMode(width, height, bpp, flags);
162     if(screen == 0) {
163       std::stringstream msg;
164       msg << "Couldn't set video mode (" << width << "x" << height
165           << "-" << bpp << "bpp): " << SDL_GetError();
166       throw std::runtime_error(msg.str());
167     }
168
169     // setup opengl state and transform
170     glDisable(GL_DEPTH_TEST);
171     glDisable(GL_CULL_FACE);
172     glEnable(GL_TEXTURE_2D);
173     glEnable(GL_BLEND);
174     glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
175
176     glViewport(0, 0, screen->w, screen->h);
177     glMatrixMode(GL_PROJECTION);
178     glLoadIdentity();
179
180     // logical resolution here not real monitor resolution
181     glOrtho(0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, -1.0, 1.0);
182
183     glMatrixMode(GL_MODELVIEW);
184     glLoadIdentity();
185     glTranslatef(0, 0, 0);
186
187     check_gl_error("Setting up view matrices");
188
189
190     if(texture_manager == 0)
191       texture_manager = new TextureManager();
192     else
193       texture_manager->reload_textures();
194   }
195
196   Renderer::~Renderer()
197   {
198   }
199
200   void
201   Renderer::draw_surface(const DrawingRequest& request)
202   {
203     const Surface* surface = (const Surface*) request.request_data;
204     GL::Texture *gltexture = dynamic_cast<GL::Texture *>(surface->get_texture());
205     GL::SurfaceData *surface_data = reinterpret_cast<GL::SurfaceData *>(surface->get_surface_data());
206
207     glBindTexture(GL_TEXTURE_2D, gltexture->get_handle());
208     intern_draw(request.pos.x, request.pos.y,
209                 request.pos.x + surface->get_width(),
210                 request.pos.y + surface->get_height(),
211                 surface_data->get_uv_left(),
212                 surface_data->get_uv_top(),
213                 surface_data->get_uv_right(),
214                 surface_data->get_uv_bottom(),
215                 request.angle,
216                 request.alpha,
217                 request.color,
218                 request.blend,
219                 request.drawing_effect);
220   }
221
222   void
223   Renderer::draw_surface_part(const DrawingRequest& request)
224   {
225     const SurfacePartRequest* surfacepartrequest
226       = (SurfacePartRequest*) request.request_data;
227     const Surface *surface = surfacepartrequest->surface;
228     GL::Texture *gltexture = dynamic_cast<GL::Texture *>(surface->get_texture());
229     GL::SurfaceData *surface_data = reinterpret_cast<GL::SurfaceData *>(surface->get_surface_data());
230
231     float uv_width = surface_data->get_uv_right() - surface_data->get_uv_left();
232     float uv_height = surface_data->get_uv_bottom() - surface_data->get_uv_top();
233
234     float uv_left = surface_data->get_uv_left() + (uv_width * surfacepartrequest->source.x) / surface->get_width();
235     float uv_top = surface_data->get_uv_top() + (uv_height * surfacepartrequest->source.y) / surface->get_height();
236     float uv_right = surface_data->get_uv_left() + (uv_width * (surfacepartrequest->source.x + surfacepartrequest->size.x)) / surface->get_width();
237     float uv_bottom = surface_data->get_uv_top() + (uv_height * (surfacepartrequest->source.y + surfacepartrequest->size.y)) / surface->get_height();
238
239     glBindTexture(GL_TEXTURE_2D, gltexture->get_handle());
240     intern_draw(request.pos.x, request.pos.y,
241                 request.pos.x + surfacepartrequest->size.x,
242                 request.pos.y + surfacepartrequest->size.y,
243                 uv_left,
244                 uv_top,
245                 uv_right,
246                 uv_bottom,
247                 0.0,
248                 request.alpha,
249                 Color(1.0, 1.0, 1.0),
250                 Blend(),
251                 request.drawing_effect);
252   }
253
254   void
255   Renderer::draw_gradient(const DrawingRequest& request)
256   {
257     const GradientRequest* gradientrequest 
258       = (GradientRequest*) request.request_data;
259     const Color& top = gradientrequest->top;
260     const Color& bottom = gradientrequest->bottom;
261
262     glDisable(GL_TEXTURE_2D);
263     glBegin(GL_QUADS);
264     glColor4f(top.red, top.green, top.blue, top.alpha);
265     glVertex2f(0, 0);
266     glVertex2f(SCREEN_WIDTH, 0);
267     glColor4f(bottom.red, bottom.green, bottom.blue, bottom.alpha);
268     glVertex2f(SCREEN_WIDTH, SCREEN_HEIGHT);
269     glVertex2f(0, SCREEN_HEIGHT);
270     glEnd();
271     glEnable(GL_TEXTURE_2D);
272     glColor4f(1, 1, 1, 1);
273   }
274
275   void
276   Renderer::draw_filled_rect(const DrawingRequest& request)
277   {
278     const FillRectRequest* fillrectrequest
279       = (FillRectRequest*) request.request_data;
280
281     if (fillrectrequest->radius != 0.0f)
282       {
283         // draw round rect
284         // Keep radius in the limits, so that we get a circle instead of
285         // just graphic junk
286         float radius = std::min(fillrectrequest->radius,
287                                 std::min(fillrectrequest->size.x/2,
288                                          fillrectrequest->size.y/2));
289
290         // inner rectangle
291         Rect irect(request.pos.x    + radius,
292                    request.pos.y    + radius,
293                    request.pos.x + fillrectrequest->size.x - radius,
294                    request.pos.y + fillrectrequest->size.y - radius);
295
296         glDisable(GL_TEXTURE_2D);
297         glColor4f(fillrectrequest->color.red, fillrectrequest->color.green,
298                   fillrectrequest->color.blue, fillrectrequest->color.alpha);
299
300
301         int n = 8;
302         glBegin(GL_QUAD_STRIP);
303         for(int i = 0; i <= n; ++i)
304           {
305             float x = sinf(i * (M_PI/2) / n) * radius;
306             float y = cosf(i * (M_PI/2) / n) * radius;
307
308             glVertex2f(irect.get_left()  - x, irect.get_top() - y);
309             glVertex2f(irect.get_right() + x, irect.get_top() - y);
310           }
311         for(int i = 0; i <= n; ++i)
312           {
313             float x = cosf(i * (M_PI/2) / n) * radius;
314             float y = sinf(i * (M_PI/2) / n) * radius;
315
316             glVertex2f(irect.get_left()  - x, irect.get_bottom() + y);
317             glVertex2f(irect.get_right() + x, irect.get_bottom() + y);
318           }
319         glEnd();
320         glEnable(GL_TEXTURE_2D);
321         glColor4f(1, 1, 1, 1);
322       }
323     else
324       {
325         float x = request.pos.x;
326         float y = request.pos.y;
327         float w = fillrectrequest->size.x;
328         float h = fillrectrequest->size.y;
329
330         glDisable(GL_TEXTURE_2D);
331         glColor4f(fillrectrequest->color.red, fillrectrequest->color.green,
332                   fillrectrequest->color.blue, fillrectrequest->color.alpha);
333
334         glBegin(GL_QUADS);
335         glVertex2f(x, y);
336         glVertex2f(x+w, y);
337         glVertex2f(x+w, y+h);
338         glVertex2f(x, y+h);
339         glEnd();
340         glEnable(GL_TEXTURE_2D);
341         glColor4f(1, 1, 1, 1);
342       }
343   }
344
345   void
346   Renderer::draw_inverse_ellipse(const DrawingRequest& request)
347   {
348     const InverseEllipseRequest* ellipse = (InverseEllipseRequest*)request.request_data;
349
350     glDisable(GL_TEXTURE_2D);
351     glColor4f(ellipse->color.red,  ellipse->color.green,
352               ellipse->color.blue, ellipse->color.alpha);
353     
354     float x = request.pos.x;
355     float y = request.pos.y;
356     float w = ellipse->size.x/2.0f;
357     float h = ellipse->size.y/2.0f;
358
359     glBegin(GL_TRIANGLES);
360     
361     // Bottom
362     glVertex2f(SCREEN_WIDTH, SCREEN_HEIGHT);
363     glVertex2f(0, SCREEN_HEIGHT);
364     glVertex2f(x, y+h);
365
366     // Top
367     glVertex2f(SCREEN_WIDTH, 0);
368     glVertex2f(0, 0);
369     glVertex2f(x, y-h);
370
371     // Left
372     glVertex2f(SCREEN_WIDTH, 0);
373     glVertex2f(SCREEN_WIDTH, SCREEN_HEIGHT);
374     glVertex2f(x+w, y);
375
376     // Right
377     glVertex2f(0, 0);
378     glVertex2f(0, SCREEN_HEIGHT);
379     glVertex2f(x-w, y);
380
381     glEnd();
382         
383     int slices = 16;
384     for(int i = 0; i < slices; ++i)
385       {
386         float ex1 = sinf(M_PI/2 / slices * i) * w;
387         float ey1 = cosf(M_PI/2 / slices * i) * h;
388
389         float ex2 = sinf(M_PI/2 / slices * (i+1)) * w;
390         float ey2 = cosf(M_PI/2 / slices * (i+1)) * h;
391
392         glBegin(GL_TRIANGLES);
393
394         // Bottom/Right
395         glVertex2f(SCREEN_WIDTH, SCREEN_HEIGHT);
396         glVertex2f(x + ex1, y + ey1);
397         glVertex2f(x + ex2, y + ey2);
398
399         // Top/Left
400         glVertex2f(0, 0);
401         glVertex2f(x - ex1, y - ey1);
402         glVertex2f(x - ex2, y - ey2);
403
404         // Top/Right
405         glVertex2f(SCREEN_WIDTH, 0);
406         glVertex2f(x + ex1, y - ey1);
407         glVertex2f(x + ex2, y - ey2);
408
409         // Bottom/Left
410         glVertex2f(0, SCREEN_HEIGHT);
411         glVertex2f(x - ex1, y + ey1);
412         glVertex2f(x - ex2, y + ey2);
413
414         glEnd();
415       }
416     glEnable(GL_TEXTURE_2D);
417     glColor4f(1, 1, 1, 1);    
418   }
419
420   void 
421   Renderer::do_take_screenshot()
422   {
423     // [Christoph] TODO: Yes, this method also takes care of the actual disk I/O. Split it?
424
425     SDL_Surface *shot_surf;
426     // create surface to hold screenshot
427     #if SDL_BYTEORDER == SDL_BIG_ENDIAN
428     shot_surf = SDL_CreateRGBSurface(SDL_SWSURFACE, SCREEN_WIDTH, SCREEN_HEIGHT, 24, 0x00FF0000, 0x0000FF00, 0x000000FF, 0);
429     #else
430     shot_surf = SDL_CreateRGBSurface(SDL_SWSURFACE, SCREEN_WIDTH, SCREEN_HEIGHT, 24, 0x000000FF, 0x0000FF00, 0x00FF0000, 0);
431     #endif
432     if (!shot_surf) {
433       log_warning << "Could not create RGB Surface to contain screenshot" << std::endl;
434       return;
435     }
436
437     // read pixels into array
438     char* pixels = new char[3 * SCREEN_WIDTH * SCREEN_HEIGHT];
439     if (!pixels) {
440       log_warning << "Could not allocate memory to store screenshot" << std::endl;
441       SDL_FreeSurface(shot_surf);
442       return;
443     }
444     glReadPixels(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, GL_RGB, GL_UNSIGNED_BYTE, pixels);
445
446     // copy array line-by-line
447     for (int i = 0; i < SCREEN_HEIGHT; i++) {
448       char* src = pixels + (3 * SCREEN_WIDTH * (SCREEN_HEIGHT - i - 1));
449       if(SDL_MUSTLOCK(shot_surf))
450       {
451         SDL_LockSurface(shot_surf);
452       }
453       char* dst = ((char*)shot_surf->pixels) + i * shot_surf->pitch;
454       memcpy(dst, src, 3 * SCREEN_WIDTH);
455       if(SDL_MUSTLOCK(shot_surf))
456       {
457         SDL_UnlockSurface(shot_surf);
458       }
459     }
460
461     // free array
462     delete[](pixels);
463
464     // save screenshot
465     static const std::string writeDir = PHYSFS_getWriteDir();
466     static const std::string dirSep = PHYSFS_getDirSeparator();
467     static const std::string baseName = "screenshot";
468     static const std::string fileExt = ".bmp";
469     std::string fullFilename;
470     for (int num = 0; num < 1000; num++) {
471       std::ostringstream oss;
472       oss << baseName;
473       oss << std::setw(3) << std::setfill('0') << num;
474       oss << fileExt;
475       std::string fileName = oss.str();
476       fullFilename = writeDir + dirSep + fileName;
477       if (!PHYSFS_exists(fileName.c_str())) {
478         SDL_SaveBMP(shot_surf, fullFilename.c_str());
479         log_debug << "Wrote screenshot to \"" << fullFilename << "\"" << std::endl;
480         SDL_FreeSurface(shot_surf);
481         return;
482       }
483     }
484     log_warning << "Did not save screenshot, because all files up to \"" << fullFilename << "\" already existed" << std::endl;
485     SDL_FreeSurface(shot_surf);
486   }
487
488   void
489   Renderer::flip()
490   {
491     assert_gl("drawing");
492     SDL_GL_SwapBuffers();
493   }
494
495   void
496   Renderer::resize(int w, int h)
497   {
498     SDL_SetVideoMode(w, h, 0, SDL_OPENGL | SDL_RESIZABLE);
499     
500     config->window_width  = w;
501     config->window_height = h;
502
503     // FIXME: Add aspect handling
504     SCREEN_WIDTH  = w;
505     SCREEN_HEIGHT = h;
506
507     glViewport(0, 0, config->window_width, config->window_height);
508     glMatrixMode(GL_PROJECTION);
509     glLoadIdentity();
510     glOrtho(0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, -1.0, 1.0);
511   }
512 }
513
514 #endif