Merge branch 'master' of https://code.google.com/p/supertux
[supertux.git] / src / video / gl / gl_renderer.cpp
1 //  SuperTux
2 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
3 //      Updated by GiBy 2013 for SDL2 <giby_the_kid@yahoo.fr>
4 //
5 //  This program is free software: you can redistribute it and/or modify
6 //  it under the terms of the GNU General Public License as published by
7 //  the Free Software Foundation, either version 3 of the License, or
8 //  (at your option) any later version.
9 //
10 //  This program is distributed in the hope that it will be useful,
11 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
12 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 //  GNU General Public License for more details.
14 //
15 //  You should have received a copy of the GNU General Public License
16 //  along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18 #include "video/gl/gl_renderer.hpp"
19
20 #include <iomanip>
21 #include <iostream>
22 #include <physfs.h>
23 #include "SDL.h"
24
25 #include "supertux/gameconfig.hpp"
26 #include "supertux/globals.hpp"
27 #include "video/drawing_request.hpp"
28 #include "video/gl/gl_surface_data.hpp"
29 #include "video/gl/gl_texture.hpp"
30 #include "video/util.hpp"
31
32 #define LIGHTMAP_DIV 5
33
34 #ifdef GL_VERSION_ES_CM_1_0
35 #  define glOrtho glOrthof
36 #endif
37
38 GLRenderer::GLRenderer() :
39   window(),
40   desktop_size(0, 0),
41   screen_size(0, 0),
42   fullscreen_active(false),
43   last_texture(static_cast<GLuint> (-1))
44 {
45   Renderer::instance_ = this;
46
47   SDL_DisplayMode mode;
48   SDL_GetCurrentDisplayMode(0, &mode);
49   desktop_size = Size(mode.w, mode.h);
50
51   if(texture_manager != 0)
52     texture_manager->save_textures();
53
54   if(g_config->try_vsync) {
55     /* we want vsync for smooth scrolling */
56     if (SDL_GL_SetSwapInterval(-1) != 0)
57     {
58       log_info << "no support for late swap tearing vsync: " << SDL_GetError() << std::endl;
59       if (SDL_GL_SetSwapInterval(1))
60       {
61         log_info << "no support for vsync: " << SDL_GetError() << std::endl;
62       }
63     }
64   }
65
66   SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
67
68   SDL_GL_SetAttribute(SDL_GL_RED_SIZE,   5);
69   SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
70   SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE,  5);
71
72   if(g_config->use_fullscreen)
73   {
74     apply_video_mode(g_config->fullscreen_size, true);
75   }
76   else
77   {
78     apply_video_mode(g_config->window_size, false);
79   }
80
81   // setup opengl state and transform
82   glDisable(GL_DEPTH_TEST);
83   glDisable(GL_CULL_FACE);
84   glEnable(GL_TEXTURE_2D);
85   glEnable(GL_BLEND);
86   glEnableClientState(GL_VERTEX_ARRAY);
87   glEnableClientState(GL_TEXTURE_COORD_ARRAY);
88   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
89
90   // Init the projection matrix, viewport and stuff
91   apply_config();
92
93   if(texture_manager == 0)
94     texture_manager = new TextureManager();
95   else
96     texture_manager->reload_textures();
97
98 #ifndef GL_VERSION_ES_CM_1_0
99   GLenum err = glewInit();
100   if (GLEW_OK != err)
101   {
102     std::ostringstream out;
103     out << "GLRenderer: " << glewGetErrorString(err);
104     throw std::runtime_error(out.str());
105   }
106   log_info << "Using GLEW " << glewGetString(GLEW_VERSION) << std::endl;
107   log_info << "GLEW_ARB_texture_non_power_of_two: " << static_cast<int>(GLEW_ARB_texture_non_power_of_two) << std::endl;
108 #endif
109 }
110
111 GLRenderer::~GLRenderer()
112 {
113   SDL_GL_DeleteContext(glcontext);
114   SDL_DestroyWindow(window);
115 }
116
117 void
118 GLRenderer::draw_surface(const DrawingRequest& request)
119 {
120   const Surface* surface = (const Surface*) request.request_data;
121   if(surface == NULL)
122   {
123     return;
124   }
125   GLTexture* gltexture = static_cast<GLTexture*>(surface->get_texture().get());
126   if(gltexture == NULL)
127   {
128     return;
129   }
130   GLSurfaceData *surface_data = static_cast<GLSurfaceData*>(surface->get_surface_data());
131   if(surface_data == NULL)
132   {
133     return;
134   }
135
136   GLuint th = gltexture->get_handle();
137   if (th != last_texture) {
138     last_texture = th;
139     glBindTexture(GL_TEXTURE_2D, th);
140   }
141   intern_draw(request.pos.x, request.pos.y,
142               request.pos.x + surface->get_width(),
143               request.pos.y + surface->get_height(),
144               surface_data->get_uv_left(),
145               surface_data->get_uv_top(),
146               surface_data->get_uv_right(),
147               surface_data->get_uv_bottom(),
148               request.angle,
149               request.alpha,
150               request.color,
151               request.blend,
152               request.drawing_effect);
153 }
154
155 void
156 GLRenderer::draw_surface_part(const DrawingRequest& request)
157 {
158   const SurfacePartRequest* surfacepartrequest
159     = (SurfacePartRequest*) request.request_data;
160   const Surface* surface = surfacepartrequest->surface;
161   boost::shared_ptr<GLTexture> gltexture = boost::dynamic_pointer_cast<GLTexture>(surface->get_texture());
162   GLSurfaceData *surface_data = reinterpret_cast<GLSurfaceData *>(surface->get_surface_data());
163
164   float uv_width = surface_data->get_uv_right() - surface_data->get_uv_left();
165   float uv_height = surface_data->get_uv_bottom() - surface_data->get_uv_top();
166
167   float uv_left = surface_data->get_uv_left() + (uv_width * surfacepartrequest->source.x) / surface->get_width();
168   float uv_top = surface_data->get_uv_top() + (uv_height * surfacepartrequest->source.y) / surface->get_height();
169   float uv_right = surface_data->get_uv_left() + (uv_width * (surfacepartrequest->source.x + surfacepartrequest->size.x)) / surface->get_width();
170   float uv_bottom = surface_data->get_uv_top() + (uv_height * (surfacepartrequest->source.y + surfacepartrequest->size.y)) / surface->get_height();
171
172   GLuint th = gltexture->get_handle();
173   if (th != last_texture) {
174     last_texture = th;
175     glBindTexture(GL_TEXTURE_2D, th);
176   }
177   intern_draw(request.pos.x, request.pos.y,
178               request.pos.x + surfacepartrequest->size.x,
179               request.pos.y + surfacepartrequest->size.y,
180               uv_left,
181               uv_top,
182               uv_right,
183               uv_bottom,
184               0.0,
185               request.alpha,
186               request.color,
187               Blend(),
188               request.drawing_effect);
189 }
190
191 void
192 GLRenderer::draw_gradient(const DrawingRequest& request)
193 {
194   const GradientRequest* gradientrequest
195     = (GradientRequest*) request.request_data;
196   const Color& top = gradientrequest->top;
197   const Color& bottom = gradientrequest->bottom;
198
199   glDisable(GL_TEXTURE_2D);
200   glDisableClientState(GL_TEXTURE_COORD_ARRAY);
201   glEnableClientState(GL_COLOR_ARRAY);
202
203   float vertices[] = {
204     0, 0,
205     float(SCREEN_WIDTH), 0,
206     float(SCREEN_WIDTH), float(SCREEN_HEIGHT),
207     0, float(SCREEN_HEIGHT)
208   };
209   glVertexPointer(2, GL_FLOAT, 0, vertices);
210
211   float colors[] = {
212     top.red, top.green, top.blue, top.alpha,
213     top.red, top.green, top.blue, top.alpha,
214     bottom.red, bottom.green, bottom.blue, bottom.alpha,
215     bottom.red, bottom.green, bottom.blue, bottom.alpha,
216   };
217   glColorPointer(4, GL_FLOAT, 0, colors);
218
219   glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
220
221   glDisableClientState(GL_COLOR_ARRAY);
222   glEnableClientState(GL_TEXTURE_COORD_ARRAY);
223
224   glEnable(GL_TEXTURE_2D);
225   glColor4f(1, 1, 1, 1);
226 }
227
228 void
229 GLRenderer::draw_filled_rect(const DrawingRequest& request)
230 {
231   const FillRectRequest* fillrectrequest
232     = (FillRectRequest*) request.request_data;
233
234   glDisable(GL_TEXTURE_2D);
235   glColor4f(fillrectrequest->color.red, fillrectrequest->color.green,
236             fillrectrequest->color.blue, fillrectrequest->color.alpha);
237   glDisableClientState(GL_TEXTURE_COORD_ARRAY);
238
239   if (fillrectrequest->radius != 0.0f)
240   {
241     // draw round rect
242     // Keep radius in the limits, so that we get a circle instead of
243     // just graphic junk
244     float radius = std::min(fillrectrequest->radius,
245                             std::min(fillrectrequest->size.x/2,
246                                      fillrectrequest->size.y/2));
247
248     // inner rectangle
249     Rectf irect(request.pos.x    + radius,
250                request.pos.y    + radius,
251                request.pos.x + fillrectrequest->size.x - radius,
252                request.pos.y + fillrectrequest->size.y - radius);
253
254     int n = 8;
255     int p = 0;
256     std::vector<float> vertices((n+1) * 4 * 2);
257
258     for(int i = 0; i <= n; ++i)
259     {
260       float x = sinf(i * (M_PI/2) / n) * radius;
261       float y = cosf(i * (M_PI/2) / n) * radius;
262
263       vertices[p++] = irect.get_left() - x;
264       vertices[p++] = irect.get_top()  - y;
265
266       vertices[p++] = irect.get_right() + x;
267       vertices[p++] = irect.get_top()   - y;
268     }
269
270     for(int i = 0; i <= n; ++i)
271     {
272       float x = cosf(i * (M_PI/2) / n) * radius;
273       float y = sinf(i * (M_PI/2) / n) * radius;
274
275       vertices[p++] = irect.get_left()   - x;
276       vertices[p++] = irect.get_bottom() + y;
277
278       vertices[p++] = irect.get_right()  + x;
279       vertices[p++] = irect.get_bottom() + y;
280     }
281
282     glVertexPointer(2, GL_FLOAT, 0, &*vertices.begin());
283     glDrawArrays(GL_TRIANGLE_STRIP, 0,  vertices.size()/2);
284   }
285   else
286   {
287     float x = request.pos.x;
288     float y = request.pos.y;
289     float w = fillrectrequest->size.x;
290     float h = fillrectrequest->size.y;
291
292     float vertices[] = {
293       x,   y,
294       x+w, y,
295       x+w, y+h,
296       x,   y+h
297     };
298     glVertexPointer(2, GL_FLOAT, 0, vertices);
299
300     glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
301   }
302
303   glEnableClientState(GL_TEXTURE_COORD_ARRAY);
304   glEnable(GL_TEXTURE_2D);
305   glColor4f(1, 1, 1, 1);
306 }
307
308 void
309 GLRenderer::draw_inverse_ellipse(const DrawingRequest& request)
310 {
311   const InverseEllipseRequest* ellipse = (InverseEllipseRequest*)request.request_data;
312
313   glDisable(GL_TEXTURE_2D);
314   glColor4f(ellipse->color.red,  ellipse->color.green,
315             ellipse->color.blue, ellipse->color.alpha);
316
317   float x = request.pos.x;
318   float y = request.pos.y;
319   float w = ellipse->size.x/2.0f;
320   float h = ellipse->size.y/2.0f;
321
322   static const int slices = 16;
323   static const int points = (slices+1) * 12;
324
325   float vertices[points * 2];
326   int   p = 0;
327
328   // Bottom
329   vertices[p++] = SCREEN_WIDTH; vertices[p++] = SCREEN_HEIGHT;
330   vertices[p++] = 0;            vertices[p++] = SCREEN_HEIGHT;
331   vertices[p++] = x;            vertices[p++] = y+h;
332
333   // Top
334   vertices[p++] = SCREEN_WIDTH; vertices[p++] = 0;
335   vertices[p++] = 0;            vertices[p++] = 0;
336   vertices[p++] = x;            vertices[p++] = y-h;
337
338   // Left
339   vertices[p++] = SCREEN_WIDTH; vertices[p++] = 0;
340   vertices[p++] = SCREEN_WIDTH; vertices[p++] = SCREEN_HEIGHT;
341   vertices[p++] = x+w;          vertices[p++] = y;
342
343   // Right
344   vertices[p++] = 0;            vertices[p++] = 0;
345   vertices[p++] = 0;            vertices[p++] = SCREEN_HEIGHT;
346   vertices[p++] = x-w;          vertices[p++] = y;
347
348   for(int i = 0; i < slices; ++i)
349   {
350     float ex1 = sinf(M_PI/2 / slices * i) * w;
351     float ey1 = cosf(M_PI/2 / slices * i) * h;
352
353     float ex2 = sinf(M_PI/2 / slices * (i+1)) * w;
354     float ey2 = cosf(M_PI/2 / slices * (i+1)) * h;
355
356     // Bottom/Right
357     vertices[p++] = SCREEN_WIDTH; vertices[p++] = SCREEN_HEIGHT;
358     vertices[p++] = x + ex1;      vertices[p++] = y + ey1;
359     vertices[p++] = x + ex2;      vertices[p++] = y + ey2;
360
361     // Top/Left
362     vertices[p++] = 0;            vertices[p++] = 0;
363     vertices[p++] = x - ex1;      vertices[p++] = y - ey1;
364     vertices[p++] = x - ex2;      vertices[p++] = y - ey2;
365
366     // Top/Right
367     vertices[p++] = SCREEN_WIDTH; vertices[p++] = 0;
368     vertices[p++] = x + ex1;      vertices[p++] = y - ey1;
369     vertices[p++] = x + ex2;      vertices[p++] = y - ey2;
370
371     // Bottom/Left
372     vertices[p++] = 0;            vertices[p++] = SCREEN_HEIGHT;
373     vertices[p++] = x - ex1;      vertices[p++] = y + ey1;
374     vertices[p++] = x - ex2;      vertices[p++] = y + ey2;
375   }
376
377   glDisableClientState(GL_TEXTURE_COORD_ARRAY);
378   glVertexPointer(2, GL_FLOAT, 0, vertices);
379
380   glDrawArrays(GL_TRIANGLES, 0, points);
381
382   glEnableClientState(GL_TEXTURE_COORD_ARRAY);
383
384   glEnable(GL_TEXTURE_2D);
385   glColor4f(1, 1, 1, 1);
386 }
387
388 void
389 GLRenderer::do_take_screenshot()
390 {
391   // [Christoph] TODO: Yes, this method also takes care of the actual disk I/O. Split it?
392
393   SDL_Surface *shot_surf;
394   // create surface to hold screenshot
395 #if SDL_BYTEORDER == SDL_BIG_ENDIAN
396   shot_surf = SDL_CreateRGBSurface(0, SCREEN_WIDTH, SCREEN_HEIGHT, 24, 0x00FF0000, 0x0000FF00, 0x000000FF, 0);
397 #else
398   shot_surf = SDL_CreateRGBSurface(0, SCREEN_WIDTH, SCREEN_HEIGHT, 24, 0x000000FF, 0x0000FF00, 0x00FF0000, 0);
399 #endif
400   if (!shot_surf) {
401     log_warning << "Could not create RGB Surface to contain screenshot" << std::endl;
402     return;
403   }
404
405   // read pixels into array
406   char* pixels = new char[3 * SCREEN_WIDTH * SCREEN_HEIGHT];
407   if (!pixels) {
408     log_warning << "Could not allocate memory to store screenshot" << std::endl;
409     SDL_FreeSurface(shot_surf);
410     return;
411   }
412   glPixelStorei(GL_PACK_ALIGNMENT, 1);
413   glReadPixels(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, GL_RGB, GL_UNSIGNED_BYTE, pixels);
414
415   // copy array line-by-line
416   for (int i = 0; i < SCREEN_HEIGHT; i++) {
417     char* src = pixels + (3 * SCREEN_WIDTH * (SCREEN_HEIGHT - i - 1));
418     if(SDL_MUSTLOCK(shot_surf))
419     {
420       SDL_LockSurface(shot_surf);
421     }
422     char* dst = ((char*)shot_surf->pixels) + i * shot_surf->pitch;
423     memcpy(dst, src, 3 * SCREEN_WIDTH);
424     if(SDL_MUSTLOCK(shot_surf))
425     {
426       SDL_UnlockSurface(shot_surf);
427     }
428   }
429
430   // free array
431   delete[](pixels);
432
433   // save screenshot
434   static const std::string writeDir = PHYSFS_getWriteDir();
435   static const std::string dirSep = PHYSFS_getDirSeparator();
436   static const std::string baseName = "screenshot";
437   static const std::string fileExt = ".bmp";
438   std::string fullFilename;
439   for (int num = 0; num < 1000; num++) {
440     std::ostringstream oss;
441     oss << baseName;
442     oss << std::setw(3) << std::setfill('0') << num;
443     oss << fileExt;
444     std::string fileName = oss.str();
445     fullFilename = writeDir + dirSep + fileName;
446     if (!PHYSFS_exists(fileName.c_str())) {
447       SDL_SaveBMP(shot_surf, fullFilename.c_str());
448       log_debug << "Wrote screenshot to \"" << fullFilename << "\"" << std::endl;
449       SDL_FreeSurface(shot_surf);
450       return;
451     }
452   }
453   log_warning << "Did not save screenshot, because all files up to \"" << fullFilename << "\" already existed" << std::endl;
454   SDL_FreeSurface(shot_surf);
455 }
456
457 void
458 GLRenderer::flip()
459 {
460   assert_gl("drawing");
461   SDL_GL_SwapWindow(window);
462 }
463
464 void
465 GLRenderer::resize(int w, int h)
466 {
467   g_config->window_size = Size(w, h);
468
469   apply_config();
470 }
471
472 void
473 GLRenderer::apply_config()
474 {
475   apply_video_mode(screen_size, g_config->use_fullscreen);
476
477   Size target_size = g_config->use_fullscreen ?
478     g_config->fullscreen_size :
479     g_config->window_size;
480
481   float pixel_aspect_ratio = 1.0f;
482   if (g_config->aspect_size != Size(0, 0))
483   {
484     pixel_aspect_ratio = calculate_pixel_aspect_ratio(desktop_size,
485                                                       g_config->aspect_size);
486   }
487   else if (g_config->use_fullscreen)
488   {
489     pixel_aspect_ratio = calculate_pixel_aspect_ratio(desktop_size,
490                                                       target_size);
491   }
492
493   Size max_size(1280, 800);
494   Size min_size(640, 480);
495
496   Vector scale;
497   Size logical_size;
498   calculate_viewport(min_size, max_size, screen_size,
499                      pixel_aspect_ratio,
500                      g_config->magnification,
501                      scale,
502                      logical_size,
503                      viewport);
504
505   SCREEN_WIDTH = logical_size.width;
506   SCREEN_HEIGHT = logical_size.height;
507
508   if (viewport.x != 0 || viewport.y != 0)
509   {
510     // Clear both buffers so that we get a clean black border without junk
511     glClear(GL_COLOR_BUFFER_BIT);
512     SDL_GL_SwapWindow(window);
513     glClear(GL_COLOR_BUFFER_BIT);
514     SDL_GL_SwapWindow(window);
515   }
516
517   glViewport(viewport.x, viewport.y, viewport.w, viewport.h);
518
519   glMatrixMode(GL_PROJECTION);
520   glLoadIdentity();
521
522   glOrtho(0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, -1, 1);
523
524   glMatrixMode(GL_MODELVIEW);
525   glLoadIdentity();
526   glTranslatef(0, 0, 0);
527   check_gl_error("Setting up view matrices");
528 }
529
530 void
531 GLRenderer::apply_video_mode(const Size& size, bool fullscreen)
532 {
533   if (window)
534   {
535     SDL_SetWindowSize(window, size.width, size.height);
536
537     if (fullscreen)
538     {
539       SDL_DisplayMode mode;
540       mode.format = SDL_PIXELFORMAT_RGB888;
541       mode.w = g_config->fullscreen_size.width;
542       mode.h = g_config->fullscreen_size.height;
543       mode.refresh_rate = g_config->fullscreen_refresh_rate;
544       mode.driverdata = 0;
545
546       if (SDL_SetWindowDisplayMode(window, &mode) != 0)
547       {
548         log_warning << "failed to set display mode: "
549                     << mode.w << "x" << mode.h << "@" << mode.refresh_rate << ": "
550                     << SDL_GetError() << std::endl;
551       }
552       else
553       {
554         SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN);
555       }
556     }
557     else
558     {
559       SDL_SetWindowFullscreen(window, 0);
560     }
561   }
562   else
563   {
564     int flags = SDL_WINDOW_OPENGL;
565
566     if (fullscreen)
567     {
568       flags |= SDL_WINDOW_FULLSCREEN;
569     }
570     else
571     {
572       flags |= SDL_WINDOW_RESIZABLE;
573     }
574
575     window = SDL_CreateWindow("SuperTux",
576                               SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
577                               size.width, size.height,
578                               flags);
579     if (!window)
580     {
581       std::ostringstream msg;
582       msg << "Couldn't set video mode " << size.width << "x" << size.height << ": " << SDL_GetError();
583       throw std::runtime_error(msg.str());
584     }
585     else
586     {
587       glcontext = SDL_GL_CreateContext(window);
588       screen_size = size;
589
590       SCREEN_WIDTH = size.width;
591       SCREEN_HEIGHT = size.height;
592
593       fullscreen_active = fullscreen;
594     }
595   }
596 }
597
598 Vector
599 GLRenderer::to_logical(int physical_x, int physical_y)
600 {
601   return Vector(static_cast<float>(physical_x - viewport.x) * SCREEN_WIDTH / viewport.w,
602                 static_cast<float>(physical_y - viewport.y) * SCREEN_HEIGHT / viewport.h);
603 }
604
605 void
606 GLRenderer::set_gamma(float gamma)
607 {
608   Uint16 ramp[256];
609   SDL_CalculateGammaRamp(gamma, ramp);
610   SDL_SetWindowGammaRamp(window, ramp, ramp, ramp);
611 }
612
613 /* EOF */