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