]> git.lizzy.rs Git - dragonfireclient.git/blob - src/guiEngine.cpp
Save minetest screen width/height options when modified (#5683)
[dragonfireclient.git] / src / guiEngine.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 sapier
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "guiEngine.h"
21
22 #include <fstream>
23 #include <IGUIStaticText.h>
24 #include <ICameraSceneNode.h>
25 #include "scripting_mainmenu.h"
26 #include "util/numeric.h"
27 #include "config.h"
28 #include "version.h"
29 #include "porting.h"
30 #include "filesys.h"
31 #include "settings.h"
32 #include "guiMainMenu.h"
33 #include "sound.h"
34 #include "sound_openal.h"
35 #include "clouds.h"
36 #include "httpfetch.h"
37 #include "log.h"
38 #include "fontengine.h"
39 #include "guiscalingfilter.h"
40 #include "irrlicht_changes/static_text.h"
41
42 #ifdef __ANDROID__
43 #include "client/tile.h"
44 #include <GLES/gl.h>
45 #endif
46
47
48 /******************************************************************************/
49 /** TextDestGuiEngine                                                         */
50 /******************************************************************************/
51 TextDestGuiEngine::TextDestGuiEngine(GUIEngine* engine)
52 {
53         m_engine = engine;
54 }
55
56 /******************************************************************************/
57 void TextDestGuiEngine::gotText(const StringMap &fields)
58 {
59         m_engine->getScriptIface()->handleMainMenuButtons(fields);
60 }
61
62 /******************************************************************************/
63 void TextDestGuiEngine::gotText(const std::wstring &text)
64 {
65         m_engine->getScriptIface()->handleMainMenuEvent(wide_to_utf8(text));
66 }
67
68 /******************************************************************************/
69 /** MenuTextureSource                                                         */
70 /******************************************************************************/
71 MenuTextureSource::MenuTextureSource(video::IVideoDriver *driver)
72 {
73         m_driver = driver;
74 }
75
76 /******************************************************************************/
77 MenuTextureSource::~MenuTextureSource()
78 {
79         for (std::set<std::string>::iterator it = m_to_delete.begin();
80                         it != m_to_delete.end(); ++it) {
81                 const char *tname = (*it).c_str();
82                 video::ITexture *texture = m_driver->getTexture(tname);
83                 m_driver->removeTexture(texture);
84         }
85 }
86
87 /******************************************************************************/
88 video::ITexture* MenuTextureSource::getTexture(const std::string &name, u32 *id)
89 {
90         if(id)
91                 *id = 0;
92         if(name.empty())
93                 return NULL;
94         m_to_delete.insert(name);
95
96 #ifdef __ANDROID__
97         video::IImage *image = m_driver->createImageFromFile(name.c_str());
98         if (image) {
99                 image = Align2Npot2(image, m_driver);
100                 video::ITexture* retval = m_driver->addTexture(name.c_str(), image);
101                 image->drop();
102                 return retval;
103         }
104 #endif
105         return m_driver->getTexture(name.c_str());
106 }
107
108 /******************************************************************************/
109 /** MenuMusicFetcher                                                          */
110 /******************************************************************************/
111 void MenuMusicFetcher::fetchSounds(const std::string &name,
112                         std::set<std::string> &dst_paths,
113                         std::set<std::string> &dst_datas)
114 {
115         if(m_fetched.count(name))
116                 return;
117         m_fetched.insert(name);
118         std::string base;
119         base = porting::path_share + DIR_DELIM + "sounds";
120         dst_paths.insert(base + DIR_DELIM + name + ".ogg");
121         int i;
122         for(i=0; i<10; i++)
123                 dst_paths.insert(base + DIR_DELIM + name + "."+itos(i)+".ogg");
124         base = porting::path_user + DIR_DELIM + "sounds";
125         dst_paths.insert(base + DIR_DELIM + name + ".ogg");
126         for(i=0; i<10; i++)
127                 dst_paths.insert(base + DIR_DELIM + name + "."+itos(i)+".ogg");
128 }
129
130 /******************************************************************************/
131 /** GUIEngine                                                                 */
132 /******************************************************************************/
133 GUIEngine::GUIEngine(   irr::IrrlichtDevice* dev,
134                                                 JoystickController *joystick,
135                                                 gui::IGUIElement* parent,
136                                                 IMenuManager *menumgr,
137                                                 scene::ISceneManager* smgr,
138                                                 MainMenuData* data,
139                                                 bool& kill) :
140         m_device(dev),
141         m_parent(parent),
142         m_menumanager(menumgr),
143         m_smgr(smgr),
144         m_data(data),
145         m_texture_source(NULL),
146         m_sound_manager(NULL),
147         m_formspecgui(0),
148         m_buttonhandler(0),
149         m_menu(0),
150         m_kill(kill),
151         m_startgame(false),
152         m_script(0),
153         m_scriptdir(""),
154         m_irr_toplefttext(0),
155         m_clouds_enabled(true),
156         m_cloud()
157 {
158         //initialize texture pointers
159         for (unsigned int i = 0; i < TEX_LAYER_MAX; i++) {
160                 m_textures[i].texture = NULL;
161         }
162         // is deleted by guiformspec!
163         m_buttonhandler = new TextDestGuiEngine(this);
164
165         //create texture source
166         m_texture_source = new MenuTextureSource(m_device->getVideoDriver());
167
168         //create soundmanager
169         MenuMusicFetcher soundfetcher;
170 #if USE_SOUND
171         m_sound_manager = createOpenALSoundManager(&soundfetcher);
172 #endif
173         if(!m_sound_manager)
174                 m_sound_manager = &dummySoundManager;
175
176         //create topleft header
177         m_toplefttext = L"";
178
179         core::rect<s32> rect(0, 0, g_fontengine->getTextWidth(m_toplefttext.c_str()),
180                 g_fontengine->getTextHeight());
181         rect += v2s32(4, 0);
182
183         m_irr_toplefttext =
184                 addStaticText(m_device->getGUIEnvironment(), m_toplefttext,
185                         rect, false, true, 0, -1);
186
187         //create formspecsource
188         m_formspecgui = new FormspecFormSource("");
189
190         /* Create menu */
191         m_menu = new GUIFormSpecMenu(m_device,
192                         joystick,
193                         m_parent,
194                         -1,
195                         m_menumanager,
196                         NULL /* &client */,
197                         m_texture_source,
198                         m_formspecgui,
199                         m_buttonhandler,
200                         false);
201
202         m_menu->allowClose(false);
203         m_menu->lockSize(true,v2u32(800,600));
204
205         // Initialize scripting
206
207         infostream << "GUIEngine: Initializing Lua" << std::endl;
208
209         m_script = new MainMenuScripting(this);
210
211         try {
212                 m_script->setMainMenuData(&m_data->script_data);
213                 m_data->script_data.errormessage = "";
214
215                 if (!loadMainMenuScript()) {
216                         errorstream << "No future without main menu!" << std::endl;
217                         abort();
218                 }
219
220                 run();
221         } catch (LuaError &e) {
222                 errorstream << "Main menu error: " << e.what() << std::endl;
223                 m_data->script_data.errormessage = e.what();
224         }
225
226         m_menu->quitMenu();
227         m_menu->drop();
228         m_menu = NULL;
229 }
230
231 /******************************************************************************/
232 bool GUIEngine::loadMainMenuScript()
233 {
234         // Set main menu path (for core.get_mainmenu_path())
235         m_scriptdir = g_settings->get("main_menu_path");
236         if (m_scriptdir.empty()) {
237                 m_scriptdir = porting::path_share + DIR_DELIM + "builtin" + DIR_DELIM + "mainmenu";
238         }
239
240         // Load builtin (which will load the main menu script)
241         std::string script = porting::path_share + DIR_DELIM "builtin" + DIR_DELIM "init.lua";
242         try {
243                 m_script->loadScript(script);
244                 // Menu script loaded
245                 return true;
246         } catch (const ModError &e) {
247                 errorstream << "GUIEngine: execution of menu script failed: "
248                         << e.what() << std::endl;
249         }
250
251         return false;
252 }
253
254 /******************************************************************************/
255 void GUIEngine::run()
256 {
257         // Always create clouds because they may or may not be
258         // needed based on the game selected
259         video::IVideoDriver* driver = m_device->getVideoDriver();
260
261         cloudInit();
262
263         unsigned int text_height = g_fontengine->getTextHeight();
264
265         irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screenW"),
266                 g_settings->getU16("screenH"));
267
268         while (m_device->run() && (!m_startgame) && (!m_kill)) {
269
270                 const irr::core::dimension2d<u32> &current_screen_size =
271                         m_device->getVideoDriver()->getScreenSize();
272                 // Verify if window size has changed and save it if it's the case
273                 // Ensure evaluating settings->getBool after verifying screensize
274                 // First condition is cheaper
275                 if (previous_screen_size != current_screen_size &&
276                                 current_screen_size != irr::core::dimension2d<u32>(0,0) &&
277                                 g_settings->getBool("autosave_screensize")) {
278                         g_settings->setU16("screenW", current_screen_size.Width);
279                         g_settings->setU16("screenH", current_screen_size.Height);
280                         previous_screen_size = current_screen_size;
281                 }
282
283                 //check if we need to update the "upper left corner"-text
284                 if (text_height != g_fontengine->getTextHeight()) {
285                         updateTopLeftTextSize();
286                         text_height = g_fontengine->getTextHeight();
287                 }
288
289                 driver->beginScene(true, true, video::SColor(255,140,186,250));
290
291                 if (m_clouds_enabled)
292                 {
293                         cloudPreProcess();
294                         drawOverlay(driver);
295                 }
296                 else
297                         drawBackground(driver);
298
299                 drawHeader(driver);
300                 drawFooter(driver);
301
302                 m_device->getGUIEnvironment()->drawAll();
303
304                 driver->endScene();
305
306                 if (m_clouds_enabled)
307                         cloudPostProcess();
308                 else
309                         sleep_ms(25);
310
311                 m_script->step();
312
313 #ifdef __ANDROID__
314                 m_menu->getAndroidUIInput();
315 #endif
316         }
317 }
318
319 /******************************************************************************/
320 GUIEngine::~GUIEngine()
321 {
322         video::IVideoDriver* driver = m_device->getVideoDriver();
323         FATAL_ERROR_IF(driver == 0, "Could not get video driver");
324
325         if(m_sound_manager != &dummySoundManager){
326                 delete m_sound_manager;
327                 m_sound_manager = NULL;
328         }
329
330         infostream<<"GUIEngine: Deinitializing scripting"<<std::endl;
331         delete m_script;
332
333         m_irr_toplefttext->setText(L"");
334
335         //clean up texture pointers
336         for (unsigned int i = 0; i < TEX_LAYER_MAX; i++) {
337                 if (m_textures[i].texture != NULL)
338                         driver->removeTexture(m_textures[i].texture);
339         }
340
341         delete m_texture_source;
342
343         if (m_cloud.clouds)
344                 m_cloud.clouds->drop();
345 }
346
347 /******************************************************************************/
348 void GUIEngine::cloudInit()
349 {
350         m_cloud.clouds = new Clouds(m_smgr->getRootSceneNode(),
351                         m_smgr, -1, rand(), 100);
352         m_cloud.clouds->update(v2f(0, 0), video::SColor(255,200,200,255));
353
354         m_cloud.camera = m_smgr->addCameraSceneNode(0,
355                                 v3f(0,0,0), v3f(0, 60, 100));
356         m_cloud.camera->setFarValue(10000);
357
358         m_cloud.lasttime = m_device->getTimer()->getTime();
359 }
360
361 /******************************************************************************/
362 void GUIEngine::cloudPreProcess()
363 {
364         u32 time = m_device->getTimer()->getTime();
365
366         if(time > m_cloud.lasttime)
367                 m_cloud.dtime = (time - m_cloud.lasttime) / 1000.0;
368         else
369                 m_cloud.dtime = 0;
370
371         m_cloud.lasttime = time;
372
373         m_cloud.clouds->step(m_cloud.dtime*3);
374         m_cloud.clouds->render();
375         m_smgr->drawAll();
376 }
377
378 /******************************************************************************/
379 void GUIEngine::cloudPostProcess()
380 {
381         float fps_max = g_settings->getFloat("pause_fps_max");
382         // Time of frame without fps limit
383         u32 busytime_u32;
384
385         // not using getRealTime is necessary for wine
386         u32 time = m_device->getTimer()->getTime();
387         if(time > m_cloud.lasttime)
388                 busytime_u32 = time - m_cloud.lasttime;
389         else
390                 busytime_u32 = 0;
391
392         // FPS limiter
393         u32 frametime_min = 1000./fps_max;
394
395         if(busytime_u32 < frametime_min) {
396                 u32 sleeptime = frametime_min - busytime_u32;
397                 m_device->sleep(sleeptime);
398         }
399 }
400
401 /******************************************************************************/
402 void GUIEngine::drawBackground(video::IVideoDriver* driver)
403 {
404         v2u32 screensize = driver->getScreenSize();
405
406         video::ITexture* texture = m_textures[TEX_LAYER_BACKGROUND].texture;
407
408         /* If no texture, draw background of solid color */
409         if(!texture){
410                 video::SColor color(255,80,58,37);
411                 core::rect<s32> rect(0, 0, screensize.X, screensize.Y);
412                 driver->draw2DRectangle(color, rect, NULL);
413                 return;
414         }
415
416         v2u32 sourcesize = texture->getOriginalSize();
417
418         if (m_textures[TEX_LAYER_BACKGROUND].tile)
419         {
420                 v2u32 tilesize(
421                                 MYMAX(sourcesize.X,m_textures[TEX_LAYER_BACKGROUND].minsize),
422                                 MYMAX(sourcesize.Y,m_textures[TEX_LAYER_BACKGROUND].minsize));
423                 for (unsigned int x = 0; x < screensize.X; x += tilesize.X )
424                 {
425                         for (unsigned int y = 0; y < screensize.Y; y += tilesize.Y )
426                         {
427                                 draw2DImageFilterScaled(driver, texture,
428                                         core::rect<s32>(x, y, x+tilesize.X, y+tilesize.Y),
429                                         core::rect<s32>(0, 0, sourcesize.X, sourcesize.Y),
430                                         NULL, NULL, true);
431                         }
432                 }
433                 return;
434         }
435
436         /* Draw background texture */
437         draw2DImageFilterScaled(driver, texture,
438                 core::rect<s32>(0, 0, screensize.X, screensize.Y),
439                 core::rect<s32>(0, 0, sourcesize.X, sourcesize.Y),
440                 NULL, NULL, true);
441 }
442
443 /******************************************************************************/
444 void GUIEngine::drawOverlay(video::IVideoDriver* driver)
445 {
446         v2u32 screensize = driver->getScreenSize();
447
448         video::ITexture* texture = m_textures[TEX_LAYER_OVERLAY].texture;
449
450         /* If no texture, draw nothing */
451         if(!texture)
452                 return;
453
454         /* Draw background texture */
455         v2u32 sourcesize = texture->getOriginalSize();
456         draw2DImageFilterScaled(driver, texture,
457                 core::rect<s32>(0, 0, screensize.X, screensize.Y),
458                 core::rect<s32>(0, 0, sourcesize.X, sourcesize.Y),
459                 NULL, NULL, true);
460 }
461
462 /******************************************************************************/
463 void GUIEngine::drawHeader(video::IVideoDriver* driver)
464 {
465         core::dimension2d<u32> screensize = driver->getScreenSize();
466
467         video::ITexture* texture = m_textures[TEX_LAYER_HEADER].texture;
468
469         /* If no texture, draw nothing */
470         if(!texture)
471                 return;
472
473         f32 mult = (((f32)screensize.Width / 2.0)) /
474                         ((f32)texture->getOriginalSize().Width);
475
476         v2s32 splashsize(((f32)texture->getOriginalSize().Width) * mult,
477                         ((f32)texture->getOriginalSize().Height) * mult);
478
479         // Don't draw the header if there isn't enough room
480         s32 free_space = (((s32)screensize.Height)-320)/2;
481
482         if (free_space > splashsize.Y) {
483                 core::rect<s32> splashrect(0, 0, splashsize.X, splashsize.Y);
484                 splashrect += v2s32((screensize.Width/2)-(splashsize.X/2),
485                                 ((free_space/2)-splashsize.Y/2)+10);
486
487         video::SColor bgcolor(255,50,50,50);
488
489         draw2DImageFilterScaled(driver, texture, splashrect,
490                 core::rect<s32>(core::position2d<s32>(0,0),
491                 core::dimension2di(texture->getOriginalSize())),
492                 NULL, NULL, true);
493         }
494 }
495
496 /******************************************************************************/
497 void GUIEngine::drawFooter(video::IVideoDriver* driver)
498 {
499         core::dimension2d<u32> screensize = driver->getScreenSize();
500
501         video::ITexture* texture = m_textures[TEX_LAYER_FOOTER].texture;
502
503         /* If no texture, draw nothing */
504         if(!texture)
505                 return;
506
507         f32 mult = (((f32)screensize.Width)) /
508                         ((f32)texture->getOriginalSize().Width);
509
510         v2s32 footersize(((f32)texture->getOriginalSize().Width) * mult,
511                         ((f32)texture->getOriginalSize().Height) * mult);
512
513         // Don't draw the footer if there isn't enough room
514         s32 free_space = (((s32)screensize.Height)-320)/2;
515
516         if (free_space > footersize.Y) {
517                 core::rect<s32> rect(0,0,footersize.X,footersize.Y);
518                 rect += v2s32(screensize.Width/2,screensize.Height-footersize.Y);
519                 rect -= v2s32(footersize.X/2, 0);
520
521                 draw2DImageFilterScaled(driver, texture, rect,
522                         core::rect<s32>(core::position2d<s32>(0,0),
523                         core::dimension2di(texture->getOriginalSize())),
524                         NULL, NULL, true);
525         }
526 }
527
528 /******************************************************************************/
529 bool GUIEngine::setTexture(texture_layer layer, std::string texturepath,
530                 bool tile_image, unsigned int minsize)
531 {
532         video::IVideoDriver* driver = m_device->getVideoDriver();
533         FATAL_ERROR_IF(driver == 0, "Could not get video driver");
534
535         if (m_textures[layer].texture != NULL)
536         {
537                 driver->removeTexture(m_textures[layer].texture);
538                 m_textures[layer].texture = NULL;
539         }
540
541         if ((texturepath == "") || !fs::PathExists(texturepath))
542         {
543                 return false;
544         }
545
546         m_textures[layer].texture = driver->getTexture(texturepath.c_str());
547         m_textures[layer].tile    = tile_image;
548         m_textures[layer].minsize = minsize;
549
550         if (m_textures[layer].texture == NULL)
551         {
552                 return false;
553         }
554
555         return true;
556 }
557
558 /******************************************************************************/
559 bool GUIEngine::downloadFile(const std::string &url, const std::string &target)
560 {
561 #if USE_CURL
562         std::ofstream target_file(target.c_str(), std::ios::out | std::ios::binary);
563
564         if (!target_file.good()) {
565                 return false;
566         }
567
568         HTTPFetchRequest fetch_request;
569         HTTPFetchResult fetch_result;
570         fetch_request.url = url;
571         fetch_request.caller = HTTPFETCH_SYNC;
572         fetch_request.timeout = g_settings->getS32("curl_file_download_timeout");
573         httpfetch_sync(fetch_request, fetch_result);
574
575         if (!fetch_result.succeeded) {
576                 return false;
577         }
578         target_file << fetch_result.data;
579
580         return true;
581 #else
582         return false;
583 #endif
584 }
585
586 /******************************************************************************/
587 void GUIEngine::setTopleftText(const std::string &text)
588 {
589         m_toplefttext = utf8_to_wide(text);
590
591         updateTopLeftTextSize();
592 }
593
594 /******************************************************************************/
595 void GUIEngine::updateTopLeftTextSize()
596 {
597         core::rect<s32> rect(0, 0, g_fontengine->getTextWidth(m_toplefttext.c_str()),
598                 g_fontengine->getTextHeight());
599         rect += v2s32(4, 0);
600
601         m_irr_toplefttext->remove();
602         m_irr_toplefttext =
603                 addStaticText(m_device->getGUIEnvironment(), m_toplefttext,
604                         rect, false, true, 0, -1);
605 }
606
607 /******************************************************************************/
608 s32 GUIEngine::playSound(SimpleSoundSpec spec, bool looped)
609 {
610         s32 handle = m_sound_manager->playSound(spec, looped);
611         return handle;
612 }
613
614 /******************************************************************************/
615 void GUIEngine::stopSound(s32 handle)
616 {
617         m_sound_manager->stopSound(handle);
618 }
619
620 /******************************************************************************/
621 unsigned int GUIEngine::queueAsync(const std::string &serialized_func,
622                 const std::string &serialized_params)
623 {
624         return m_script->queueAsync(serialized_func, serialized_params);
625 }
626