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