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