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