]> git.lizzy.rs Git - dragonfireclient.git/blob - src/script/cpp_api/s_base.cpp
Expose getPointedThing to Lua
[dragonfireclient.git] / src / script / cpp_api / s_base.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
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 "cpp_api/s_base.h"
21 #include "cpp_api/s_internal.h"
22 #include "cpp_api/s_security.h"
23 #include "lua_api/l_object.h"
24 #include "common/c_converter.h"
25 #include "serverobject.h"
26 #include "filesys.h"
27 #include "mods.h"
28 #include "porting.h"
29 #include "util/string.h"
30 #include "server.h"
31 #ifndef SERVER
32 #include "client.h"
33 #endif
34
35
36 extern "C" {
37 #include "lualib.h"
38 #if USE_LUAJIT
39         #include "luajit.h"
40 #endif
41 }
42
43 #include <stdio.h>
44 #include <cstdarg>
45 #include "script/common/c_content.h"
46 #include <sstream>
47
48
49 class ModNameStorer
50 {
51 private:
52         lua_State *L;
53 public:
54         ModNameStorer(lua_State *L_, const std::string &mod_name):
55                 L(L_)
56         {
57                 // Store current mod name in registry
58                 lua_pushstring(L, mod_name.c_str());
59                 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
60         }
61         ~ModNameStorer()
62         {
63                 // Clear current mod name from registry
64                 lua_pushnil(L);
65                 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
66         }
67 };
68
69
70 /*
71         ScriptApiBase
72 */
73
74 ScriptApiBase::ScriptApiBase()
75 {
76 #ifdef SCRIPTAPI_LOCK_DEBUG
77         m_lock_recursion_count = 0;
78 #endif
79
80         m_luastack = luaL_newstate();
81         FATAL_ERROR_IF(!m_luastack, "luaL_newstate() failed");
82
83         lua_atpanic(m_luastack, &luaPanic);
84
85         luaL_openlibs(m_luastack);
86
87         // Make the ScriptApiBase* accessible to ModApiBase
88         lua_pushlightuserdata(m_luastack, this);
89         lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
90
91         // Add and save an error handler
92         lua_getglobal(m_luastack, "debug");
93         lua_getfield(m_luastack, -1, "traceback");
94         lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_BACKTRACE);
95         lua_pop(m_luastack, 1); // pop debug
96
97         // If we are using LuaJIT add a C++ wrapper function to catch
98         // exceptions thrown in Lua -> C++ calls
99 #if USE_LUAJIT
100         lua_pushlightuserdata(m_luastack, (void*) script_exception_wrapper);
101         luaJIT_setmode(m_luastack, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON);
102         lua_pop(m_luastack, 1);
103 #endif
104
105         // Add basic globals
106         lua_newtable(m_luastack);
107         lua_setglobal(m_luastack, "core");
108
109         lua_pushstring(m_luastack, DIR_DELIM);
110         lua_setglobal(m_luastack, "DIR_DELIM");
111
112         lua_pushstring(m_luastack, porting::getPlatformName());
113         lua_setglobal(m_luastack, "PLATFORM");
114 }
115
116 ScriptApiBase::~ScriptApiBase()
117 {
118         lua_close(m_luastack);
119 }
120
121 int ScriptApiBase::luaPanic(lua_State *L)
122 {
123         std::ostringstream oss;
124         oss << "LUA PANIC: unprotected error in call to Lua API ("
125                 << lua_tostring(L, -1) << ")";
126         FATAL_ERROR(oss.str().c_str());
127         // NOTREACHED
128         return 0;
129 }
130
131 void ScriptApiBase::loadMod(const std::string &script_path,
132                 const std::string &mod_name)
133 {
134         ModNameStorer mod_name_storer(getStack(), mod_name);
135
136         loadScript(script_path);
137 }
138
139 void ScriptApiBase::loadScript(const std::string &script_path)
140 {
141         verbosestream << "Loading and running script from " << script_path << std::endl;
142
143         lua_State *L = getStack();
144
145         int error_handler = PUSH_ERROR_HANDLER(L);
146
147         bool ok;
148         if (m_secure) {
149                 ok = ScriptApiSecurity::safeLoadFile(L, script_path.c_str());
150         } else {
151                 ok = !luaL_loadfile(L, script_path.c_str());
152         }
153         ok = ok && !lua_pcall(L, 0, 0, error_handler);
154         if (!ok) {
155                 std::string error_msg = lua_tostring(L, -1);
156                 lua_pop(L, 2); // Pop error message and error handler
157                 throw ModError("Failed to load and run script from " +
158                                 script_path + ":\n" + error_msg);
159         }
160         lua_pop(L, 1); // Pop error handler
161 }
162
163 #ifndef SERVER
164 void ScriptApiBase::loadModFromMemory(const std::string &mod_name)
165 {
166         ModNameStorer mod_name_storer(getStack(), mod_name);
167
168         const std::string *init_filename = getClient()->getModFile(mod_name + ":init.lua");
169         const std::string display_filename = mod_name + ":init.lua";
170         if(init_filename == NULL)
171                 throw ModError("Mod:\"" + mod_name + "\" lacks init.lua");
172
173         verbosestream << "Loading and running script " << display_filename << std::endl;
174
175         lua_State *L = getStack();
176
177         int error_handler = PUSH_ERROR_HANDLER(L);
178
179         bool ok = ScriptApiSecurity::safeLoadFile(L, init_filename->c_str(), display_filename.c_str());
180         if (ok)
181                 ok = !lua_pcall(L, 0, 0, error_handler);
182         if (!ok) {
183                 std::string error_msg = luaL_checkstring(L, -1);
184                 lua_pop(L, 2); // Pop error message and error handler
185                 throw ModError("Failed to load and run mod \"" +
186                                 mod_name + "\":\n" + error_msg);
187         }
188         lua_pop(L, 1); // Pop error handler
189 }
190 #endif
191
192 // Push the list of callbacks (a lua table).
193 // Then push nargs arguments.
194 // Then call this function, which
195 // - runs the callbacks
196 // - replaces the table and arguments with the return value,
197 //     computed depending on mode
198 // This function must only be called with scriptlock held (i.e. inside of a
199 // code block with SCRIPTAPI_PRECHECKHEADER declared)
200 void ScriptApiBase::runCallbacksRaw(int nargs,
201                 RunCallbacksMode mode, const char *fxn)
202 {
203 #ifdef SCRIPTAPI_LOCK_DEBUG
204         assert(m_lock_recursion_count > 0);
205 #endif
206         lua_State *L = getStack();
207         FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
208
209         // Insert error handler
210         PUSH_ERROR_HANDLER(L);
211         int error_handler = lua_gettop(L) - nargs - 1;
212         lua_insert(L, error_handler);
213
214         // Insert run_callbacks between error handler and table
215         lua_getglobal(L, "core");
216         lua_getfield(L, -1, "run_callbacks");
217         lua_remove(L, -2);
218         lua_insert(L, error_handler + 1);
219
220         // Insert mode after table
221         lua_pushnumber(L, (int)mode);
222         lua_insert(L, error_handler + 3);
223
224         // Stack now looks like this:
225         // ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n>
226
227         int result = lua_pcall(L, nargs + 2, 1, error_handler);
228         if (result != 0)
229                 scriptError(result, fxn);
230
231         lua_remove(L, error_handler);
232 }
233
234 void ScriptApiBase::realityCheck()
235 {
236         int top = lua_gettop(m_luastack);
237         if (top >= 30) {
238                 dstream << "Stack is over 30:" << std::endl;
239                 stackDump(dstream);
240                 std::string traceback = script_get_backtrace(m_luastack);
241                 throw LuaError("Stack is over 30 (reality check)\n" + traceback);
242         }
243 }
244
245 void ScriptApiBase::scriptError(int result, const char *fxn)
246 {
247         script_error(getStack(), result, m_last_run_mod.c_str(), fxn);
248 }
249
250 void ScriptApiBase::stackDump(std::ostream &o)
251 {
252         int top = lua_gettop(m_luastack);
253         for (int i = 1; i <= top; i++) {  /* repeat for each level */
254                 int t = lua_type(m_luastack, i);
255                 switch (t) {
256                         case LUA_TSTRING:  /* strings */
257                                 o << "\"" << lua_tostring(m_luastack, i) << "\"";
258                                 break;
259                         case LUA_TBOOLEAN:  /* booleans */
260                                 o << (lua_toboolean(m_luastack, i) ? "true" : "false");
261                                 break;
262                         case LUA_TNUMBER:  /* numbers */ {
263                                 char buf[10];
264                                 snprintf(buf, 10, "%lf", lua_tonumber(m_luastack, i));
265                                 o << buf;
266                                 break;
267                         }
268                         default:  /* other values */
269                                 o << lua_typename(m_luastack, t);
270                                 break;
271                 }
272                 o << " ";
273         }
274         o << std::endl;
275 }
276
277 void ScriptApiBase::setOriginDirect(const char *origin)
278 {
279         m_last_run_mod = origin ? origin : "??";
280 }
281
282 void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn)
283 {
284 #ifdef SCRIPTAPI_DEBUG
285         lua_State *L = getStack();
286
287         m_last_run_mod = lua_istable(L, index) ?
288                 getstringfield_default(L, index, "mod_origin", "") : "";
289         //printf(">>>> running %s for mod: %s\n", fxn, m_last_run_mod.c_str());
290 #endif
291 }
292
293 void ScriptApiBase::addObjectReference(ServerActiveObject *cobj)
294 {
295         SCRIPTAPI_PRECHECKHEADER
296         //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
297
298         // Create object on stack
299         ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
300         int object = lua_gettop(L);
301
302         // Get core.object_refs table
303         lua_getglobal(L, "core");
304         lua_getfield(L, -1, "object_refs");
305         luaL_checktype(L, -1, LUA_TTABLE);
306         int objectstable = lua_gettop(L);
307
308         // object_refs[id] = object
309         lua_pushnumber(L, cobj->getId()); // Push id
310         lua_pushvalue(L, object); // Copy object to top of stack
311         lua_settable(L, objectstable);
312 }
313
314 void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj)
315 {
316         SCRIPTAPI_PRECHECKHEADER
317         //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
318
319         // Get core.object_refs table
320         lua_getglobal(L, "core");
321         lua_getfield(L, -1, "object_refs");
322         luaL_checktype(L, -1, LUA_TTABLE);
323         int objectstable = lua_gettop(L);
324
325         // Get object_refs[id]
326         lua_pushnumber(L, cobj->getId()); // Push id
327         lua_gettable(L, objectstable);
328         // Set object reference to NULL
329         ObjectRef::set_null(L);
330         lua_pop(L, 1); // pop object
331
332         // Set object_refs[id] = nil
333         lua_pushnumber(L, cobj->getId()); // Push id
334         lua_pushnil(L);
335         lua_settable(L, objectstable);
336 }
337
338 // Creates a new anonymous reference if cobj=NULL or id=0
339 void ScriptApiBase::objectrefGetOrCreate(lua_State *L,
340                 ServerActiveObject *cobj)
341 {
342         if (cobj == NULL || cobj->getId() == 0) {
343                 ObjectRef::create(L, cobj);
344         } else {
345                 push_objectRef(L, cobj->getId());
346         }
347 }
348
349 Server* ScriptApiBase::getServer()
350 {
351         return dynamic_cast<Server *>(m_gamedef);
352 }
353 #ifndef SERVER
354 Client* ScriptApiBase::getClient()
355 {
356         return dynamic_cast<Client *>(m_gamedef);
357 }
358 #endif