Updated addon repository URL and improved debug output on download
[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_painter.hpp"
29 #include "video/gl/gl_surface_data.hpp"
30 #include "video/gl/gl_texture.hpp"
31 #include "video/util.hpp"
32
33 #ifdef USE_GLBINDING
34 #  include <glbinding/ContextInfo.h>
35 #  include <glbinding/gl/extension.h>
36 #  include <glbinding/callbacks.h>
37 #endif
38
39 #define LIGHTMAP_DIV 5
40
41 #ifdef GL_VERSION_ES_CM_1_0
42 #  define glOrtho glOrthof
43 #endif
44
45 GLRenderer::GLRenderer() :
46   m_window(),
47   m_glcontext(),
48   m_viewport(),
49   m_desktop_size(0, 0),
50   m_fullscreen_active(false)
51 {
52   SDL_DisplayMode mode;
53   SDL_GetCurrentDisplayMode(0, &mode);
54   m_desktop_size = Size(mode.w, mode.h);
55
56   if(g_config->try_vsync) {
57     /* we want vsync for smooth scrolling */
58     if (SDL_GL_SetSwapInterval(-1) != 0)
59     {
60       log_info << "no support for late swap tearing vsync: " << SDL_GetError() << std::endl;
61       if (SDL_GL_SetSwapInterval(1))
62       {
63         log_info << "no support for vsync: " << SDL_GetError() << std::endl;
64       }
65     }
66   }
67
68   SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
69
70   SDL_GL_SetAttribute(SDL_GL_RED_SIZE,   5);
71   SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
72   SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE,  5);
73
74   apply_video_mode();
75
76 #ifdef USE_GLBINDING
77
78   glbinding::Binding::initialize();
79
80 #ifdef USE_GLBINDING_DEBUG_OUTPUT
81   glbinding::setCallbackMask(glbinding::CallbackMask::After | glbinding::CallbackMask::ParametersAndReturnValue);
82
83   glbinding::setAfterCallback([](const glbinding::FunctionCall & call) {
84     std::cout << call.function.name() << "(";
85
86     for (unsigned i = 0; i < call.parameters.size(); ++i)
87     {
88       std::cout << call.parameters[i]->asString();
89       if (i < call.parameters.size() - 1)
90         std::cout << ", ";
91     }
92
93       std::cout << ")";
94
95     if (call.returnValue)
96     {
97       std::cout << " -> " << call.returnValue->asString();
98     }
99
100     std::cout << std::endl;
101   });
102 #endif
103
104   static auto extensions = glbinding::ContextInfo::extensions();
105   log_info << "Using glbinding 1.0.0 " << std::endl;
106   log_info << "ARB_texture_non_power_of_two: " << static_cast<int>(extensions.find(GLextension::GL_ARB_texture_non_power_of_two) != extensions.end()) << std::endl;
107
108 #endif
109
110   // setup opengl state and transform
111   glDisable(GL_DEPTH_TEST);
112   glDisable(GL_CULL_FACE);
113   glEnable(GL_TEXTURE_2D);
114   glEnable(GL_BLEND);
115   glEnableClientState(GL_VERTEX_ARRAY);
116   glEnableClientState(GL_TEXTURE_COORD_ARRAY);
117   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
118
119   // Init the projection matrix, viewport and stuff
120   apply_config();
121
122 #ifndef GL_VERSION_ES_CM_1_0
123   #ifndef USE_GLBINDING
124   GLenum err = glewInit();
125   if (GLEW_OK != err)
126   {
127     std::ostringstream out;
128     out << "GLRenderer: " << glewGetErrorString(err);
129     throw std::runtime_error(out.str());
130   }
131   log_info << "Using GLEW " << glewGetString(GLEW_VERSION) << std::endl;
132   log_info << "GLEW_ARB_texture_non_power_of_two: " << static_cast<int>(GLEW_ARB_texture_non_power_of_two) << std::endl;
133 #  endif
134 #endif
135 }
136
137 GLRenderer::~GLRenderer()
138 {
139   SDL_GL_DeleteContext(m_glcontext);
140   SDL_DestroyWindow(m_window);
141 }
142
143 void
144 GLRenderer::do_take_screenshot()
145 {
146   // [Christoph] TODO: Yes, this method also takes care of the actual disk I/O. Split it?
147
148   SDL_Surface *shot_surf;
149   // create surface to hold screenshot
150 #if SDL_BYTEORDER == SDL_BIG_ENDIAN
151   shot_surf = SDL_CreateRGBSurface(0, SCREEN_WIDTH, SCREEN_HEIGHT, 24, 0x00FF0000, 0x0000FF00, 0x000000FF, 0);
152 #else
153   shot_surf = SDL_CreateRGBSurface(0, SCREEN_WIDTH, SCREEN_HEIGHT, 24, 0x000000FF, 0x0000FF00, 0x00FF0000, 0);
154 #endif
155   if (!shot_surf) {
156     log_warning << "Could not create RGB Surface to contain screenshot" << std::endl;
157     return;
158   }
159
160   // read pixels into array
161   char* pixels = new char[3 * SCREEN_WIDTH * SCREEN_HEIGHT];
162   if (!pixels) {
163     log_warning << "Could not allocate memory to store screenshot" << std::endl;
164     SDL_FreeSurface(shot_surf);
165     return;
166   }
167   glPixelStorei(GL_PACK_ALIGNMENT, 1);
168   glReadPixels(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, GL_RGB, GL_UNSIGNED_BYTE, pixels);
169
170   // copy array line-by-line
171   for (int i = 0; i < SCREEN_HEIGHT; i++) {
172     char* src = pixels + (3 * SCREEN_WIDTH * (SCREEN_HEIGHT - i - 1));
173     if(SDL_MUSTLOCK(shot_surf))
174     {
175       SDL_LockSurface(shot_surf);
176     }
177     char* dst = ((char*)shot_surf->pixels) + i * shot_surf->pitch;
178     memcpy(dst, src, 3 * SCREEN_WIDTH);
179     if(SDL_MUSTLOCK(shot_surf))
180     {
181       SDL_UnlockSurface(shot_surf);
182     }
183   }
184
185   // free array
186   delete[](pixels);
187
188   // save screenshot
189   static const std::string writeDir = PHYSFS_getWriteDir();
190   static const std::string dirSep = PHYSFS_getDirSeparator();
191   static const std::string baseName = "screenshot";
192   static const std::string fileExt = ".bmp";
193   std::string fullFilename;
194   for (int num = 0; num < 1000; num++) {
195     std::ostringstream oss;
196     oss << baseName;
197     oss << std::setw(3) << std::setfill('0') << num;
198     oss << fileExt;
199     std::string fileName = oss.str();
200     fullFilename = writeDir + dirSep + fileName;
201     if (!PHYSFS_exists(fileName.c_str())) {
202       SDL_SaveBMP(shot_surf, fullFilename.c_str());
203       log_info << "Wrote screenshot to \"" << fullFilename << "\"" << std::endl;
204       SDL_FreeSurface(shot_surf);
205       return;
206     }
207   }
208   log_warning << "Did not save screenshot, because all files up to \"" << fullFilename << "\" already existed" << std::endl;
209   SDL_FreeSurface(shot_surf);
210 }
211
212 void
213 GLRenderer::flip()
214 {
215   assert_gl("drawing");
216   SDL_GL_SwapWindow(m_window);
217 }
218
219 void
220 GLRenderer::resize(int w, int h)
221 {
222   g_config->window_size = Size(w, h);
223
224   apply_config();
225 }
226
227 void
228 GLRenderer::apply_config()
229 {
230   apply_video_mode();
231
232   Size target_size = g_config->use_fullscreen ?
233     ((g_config->fullscreen_size == Size(0, 0)) ? m_desktop_size : g_config->fullscreen_size) :
234     g_config->window_size;
235
236   float pixel_aspect_ratio = 1.0f;
237   if (g_config->aspect_size != Size(0, 0))
238   {
239     pixel_aspect_ratio = calculate_pixel_aspect_ratio(m_desktop_size,
240                                                       g_config->aspect_size);
241   }
242   else if (g_config->use_fullscreen)
243   {
244     pixel_aspect_ratio = calculate_pixel_aspect_ratio(m_desktop_size,
245                                                       target_size);
246   }
247
248   Size max_size(1280, 800);
249   Size min_size(640, 480);
250
251   Vector scale;
252   Size logical_size;
253   calculate_viewport(min_size, max_size, target_size,
254                      pixel_aspect_ratio,
255                      g_config->magnification,
256                      scale,
257                      logical_size,
258                      m_viewport);
259
260   SCREEN_WIDTH = logical_size.width;
261   SCREEN_HEIGHT = logical_size.height;
262
263   if (m_viewport.x != 0 || m_viewport.y != 0)
264   {
265     // Clear both buffers so that we get a clean black border without junk
266     glClear(GL_COLOR_BUFFER_BIT);
267     SDL_GL_SwapWindow(m_window);
268     glClear(GL_COLOR_BUFFER_BIT);
269     SDL_GL_SwapWindow(m_window);
270   }
271
272   glViewport(m_viewport.x, m_viewport.y, m_viewport.w, m_viewport.h);
273
274   glMatrixMode(GL_PROJECTION);
275   glLoadIdentity();
276
277   glOrtho(0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, -1, 1);
278
279   glMatrixMode(GL_MODELVIEW);
280   glLoadIdentity();
281   glTranslatef(0, 0, 0);
282   check_gl_error("Setting up view matrices");
283 }
284
285 void
286 GLRenderer::apply_video_mode()
287 {
288   if (m_window)
289   {
290     if (!g_config->use_fullscreen)
291     {
292       SDL_SetWindowFullscreen(m_window, 0);
293     }
294     else
295     {
296       if (g_config->fullscreen_size.width == 0 &&
297           g_config->fullscreen_size.height == 0)
298       {
299         if (SDL_SetWindowFullscreen(m_window, SDL_WINDOW_FULLSCREEN_DESKTOP) != 0)
300         {
301           log_warning << "failed to switch to desktop fullscreen mode: "
302                       << SDL_GetError() << std::endl;
303         }
304         else
305         {
306           log_info << "switched to desktop fullscreen mode" << std::endl;
307         }
308       }
309       else
310       {
311         SDL_DisplayMode mode;
312         mode.format = SDL_PIXELFORMAT_RGB888;
313         mode.w = g_config->fullscreen_size.width;
314         mode.h = g_config->fullscreen_size.height;
315         mode.refresh_rate = g_config->fullscreen_refresh_rate;
316         mode.driverdata = 0;
317
318         if (SDL_SetWindowDisplayMode(m_window, &mode) != 0)
319         {
320           log_warning << "failed to set display mode: "
321                       << mode.w << "x" << mode.h << "@" << mode.refresh_rate << ": "
322                       << SDL_GetError() << std::endl;
323         }
324         else
325         {
326           if (SDL_SetWindowFullscreen(m_window, SDL_WINDOW_FULLSCREEN) != 0)
327           {
328             log_warning << "failed to switch to fullscreen mode: "
329                         << mode.w << "x" << mode.h << "@" << mode.refresh_rate << ": "
330                         << SDL_GetError() << std::endl;
331           }
332           else
333           {
334             log_info << "switched to fullscreen mode: "
335                      << mode.w << "x" << mode.h << "@" << mode.refresh_rate << std::endl;
336           }
337         }
338       }
339     }
340   }
341   else
342   {
343     int flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE;
344     Size size;
345     if (g_config->use_fullscreen)
346     {
347       if (g_config->fullscreen_size == Size(0, 0))
348       {
349         flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
350         size = m_desktop_size;
351       }
352       else
353       {
354         flags |= SDL_WINDOW_FULLSCREEN;
355         size.width  = g_config->fullscreen_size.width;
356         size.height = g_config->fullscreen_size.height;
357       }
358     }
359     else
360     {
361       size = g_config->window_size;
362     }
363
364     m_window = SDL_CreateWindow("SuperTux",
365                               SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
366                               size.width, size.height,
367                               flags);
368     if (!m_window)
369     {
370       std::ostringstream msg;
371       msg << "Couldn't set video mode " << size.width << "x" << size.height << ": " << SDL_GetError();
372       throw std::runtime_error(msg.str());
373     }
374     else
375     {
376       m_glcontext = SDL_GL_CreateContext(m_window);
377
378       SCREEN_WIDTH = size.width;
379       SCREEN_HEIGHT = size.height;
380
381       m_fullscreen_active = g_config->use_fullscreen;
382     }
383   }
384 }
385
386 void
387 GLRenderer::start_draw()
388 {
389 }
390
391 void
392 GLRenderer::end_draw()
393 {
394 }
395
396 void
397 GLRenderer::draw_surface(const DrawingRequest& request)
398 {
399   GLPainter::draw_surface(request);
400 }
401
402 void
403 GLRenderer::draw_surface_part(const DrawingRequest& request)
404 {
405   GLPainter::draw_surface_part(request);
406 }
407
408 void
409 GLRenderer::draw_gradient(const DrawingRequest& request)
410 {
411   GLPainter::draw_gradient(request);
412 }
413
414 void
415 GLRenderer::draw_filled_rect(const DrawingRequest& request)
416 {
417   GLPainter::draw_filled_rect(request);
418 }
419
420 void
421 GLRenderer::draw_inverse_ellipse(const DrawingRequest& request)
422 {
423   GLPainter::draw_inverse_ellipse(request);
424 }
425
426 Vector
427 GLRenderer::to_logical(int physical_x, int physical_y)
428 {
429   return Vector(static_cast<float>(physical_x - m_viewport.x) * SCREEN_WIDTH / m_viewport.w,
430                 static_cast<float>(physical_y - m_viewport.y) * SCREEN_HEIGHT / m_viewport.h);
431 }
432
433 void
434 GLRenderer::set_gamma(float gamma)
435 {
436   Uint16 ramp[256];
437   SDL_CalculateGammaRamp(gamma, ramp);
438   SDL_SetWindowGammaRamp(m_window, ramp, ramp, ramp);
439 }
440
441 /* EOF */