Predict param2 of facedir nodes and attachment of attached_node nodes
[oweals/minetest.git] / src / scriptapi_nodemeta.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 "scriptapi.h"
21 #include "scriptapi_nodemeta.h"
22 #include "map.h"
23 #include "script.h"
24 #include "scriptapi_types.h"
25 #include "scriptapi_inventory.h"
26 #include "scriptapi_common.h"
27 #include "scriptapi_item.h"
28 #include "scriptapi_object.h"
29
30
31 /*
32         NodeMetaRef
33 */
34 NodeMetaRef* NodeMetaRef::checkobject(lua_State *L, int narg)
35 {
36         luaL_checktype(L, narg, LUA_TUSERDATA);
37         void *ud = luaL_checkudata(L, narg, className);
38         if(!ud) luaL_typerror(L, narg, className);
39         return *(NodeMetaRef**)ud;  // unbox pointer
40 }
41
42 NodeMetadata* NodeMetaRef::getmeta(NodeMetaRef *ref, bool auto_create)
43 {
44         NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
45         if(meta == NULL && auto_create)
46         {
47                 meta = new NodeMetadata(ref->m_env->getGameDef());
48                 ref->m_env->getMap().setNodeMetadata(ref->m_p, meta);
49         }
50         return meta;
51 }
52
53 void NodeMetaRef::reportMetadataChange(NodeMetaRef *ref)
54 {
55         // NOTE: This same code is in rollback_interface.cpp
56         // Inform other things that the metadata has changed
57         v3s16 blockpos = getNodeBlockPos(ref->m_p);
58         MapEditEvent event;
59         event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
60         event.p = blockpos;
61         ref->m_env->getMap().dispatchEvent(&event);
62         // Set the block to be saved
63         MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
64         if(block)
65                 block->raiseModified(MOD_STATE_WRITE_NEEDED,
66                                 "NodeMetaRef::reportMetadataChange");
67 }
68
69 // Exported functions
70
71 // garbage collector
72 int NodeMetaRef::gc_object(lua_State *L) {
73         NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
74         delete o;
75         return 0;
76 }
77
78 // get_string(self, name)
79 int NodeMetaRef::l_get_string(lua_State *L)
80 {
81         NodeMetaRef *ref = checkobject(L, 1);
82         std::string name = luaL_checkstring(L, 2);
83
84         NodeMetadata *meta = getmeta(ref, false);
85         if(meta == NULL){
86                 lua_pushlstring(L, "", 0);
87                 return 1;
88         }
89         std::string str = meta->getString(name);
90         lua_pushlstring(L, str.c_str(), str.size());
91         return 1;
92 }
93
94 // set_string(self, name, var)
95 int NodeMetaRef::l_set_string(lua_State *L)
96 {
97         NodeMetaRef *ref = checkobject(L, 1);
98         std::string name = luaL_checkstring(L, 2);
99         size_t len = 0;
100         const char *s = lua_tolstring(L, 3, &len);
101         std::string str(s, len);
102
103         NodeMetadata *meta = getmeta(ref, !str.empty());
104         if(meta == NULL || str == meta->getString(name))
105                 return 0;
106         meta->setString(name, str);
107         reportMetadataChange(ref);
108         return 0;
109 }
110
111 // get_int(self, name)
112 int NodeMetaRef::l_get_int(lua_State *L)
113 {
114         NodeMetaRef *ref = checkobject(L, 1);
115         std::string name = lua_tostring(L, 2);
116
117         NodeMetadata *meta = getmeta(ref, false);
118         if(meta == NULL){
119                 lua_pushnumber(L, 0);
120                 return 1;
121         }
122         std::string str = meta->getString(name);
123         lua_pushnumber(L, stoi(str));
124         return 1;
125 }
126
127 // set_int(self, name, var)
128 int NodeMetaRef::l_set_int(lua_State *L)
129 {
130         NodeMetaRef *ref = checkobject(L, 1);
131         std::string name = lua_tostring(L, 2);
132         int a = lua_tointeger(L, 3);
133         std::string str = itos(a);
134
135         NodeMetadata *meta = getmeta(ref, true);
136         if(meta == NULL || str == meta->getString(name))
137                 return 0;
138         meta->setString(name, str);
139         reportMetadataChange(ref);
140         return 0;
141 }
142
143 // get_float(self, name)
144 int NodeMetaRef::l_get_float(lua_State *L)
145 {
146         NodeMetaRef *ref = checkobject(L, 1);
147         std::string name = lua_tostring(L, 2);
148
149         NodeMetadata *meta = getmeta(ref, false);
150         if(meta == NULL){
151                 lua_pushnumber(L, 0);
152                 return 1;
153         }
154         std::string str = meta->getString(name);
155         lua_pushnumber(L, stof(str));
156         return 1;
157 }
158
159 // set_float(self, name, var)
160 int NodeMetaRef::l_set_float(lua_State *L)
161 {
162         NodeMetaRef *ref = checkobject(L, 1);
163         std::string name = lua_tostring(L, 2);
164         float a = lua_tonumber(L, 3);
165         std::string str = ftos(a);
166
167         NodeMetadata *meta = getmeta(ref, true);
168         if(meta == NULL || str == meta->getString(name))
169                 return 0;
170         meta->setString(name, str);
171         reportMetadataChange(ref);
172         return 0;
173 }
174
175 // get_inventory(self)
176 int NodeMetaRef::l_get_inventory(lua_State *L)
177 {
178         NodeMetaRef *ref = checkobject(L, 1);
179         getmeta(ref, true);  // try to ensure the metadata exists
180         InvRef::createNodeMeta(L, ref->m_p);
181         return 1;
182 }
183
184 // to_table(self)
185 int NodeMetaRef::l_to_table(lua_State *L)
186 {
187         NodeMetaRef *ref = checkobject(L, 1);
188
189         NodeMetadata *meta = getmeta(ref, true);
190         if(meta == NULL){
191                 lua_pushnil(L);
192                 return 1;
193         }
194         lua_newtable(L);
195         // fields
196         lua_newtable(L);
197         {
198                 std::map<std::string, std::string> fields = meta->getStrings();
199                 for(std::map<std::string, std::string>::const_iterator
200                                 i = fields.begin(); i != fields.end(); i++){
201                         const std::string &name = i->first;
202                         const std::string &value = i->second;
203                         lua_pushlstring(L, name.c_str(), name.size());
204                         lua_pushlstring(L, value.c_str(), value.size());
205                         lua_settable(L, -3);
206                 }
207         }
208         lua_setfield(L, -2, "fields");
209         // inventory
210         lua_newtable(L);
211         Inventory *inv = meta->getInventory();
212         if(inv){
213                 std::vector<const InventoryList*> lists = inv->getLists();
214                 for(std::vector<const InventoryList*>::const_iterator
215                                 i = lists.begin(); i != lists.end(); i++){
216                         inventory_get_list_to_lua(inv, (*i)->getName().c_str(), L);
217                         lua_setfield(L, -2, (*i)->getName().c_str());
218                 }
219         }
220         lua_setfield(L, -2, "inventory");
221         return 1;
222 }
223
224 // from_table(self, table)
225 int NodeMetaRef::l_from_table(lua_State *L)
226 {
227         NodeMetaRef *ref = checkobject(L, 1);
228         int base = 2;
229
230         if(lua_isnil(L, base)){
231                 // No metadata
232                 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
233                 lua_pushboolean(L, true);
234                 return 1;
235         }
236
237         // Has metadata; clear old one first
238         ref->m_env->getMap().removeNodeMetadata(ref->m_p);
239         // Create new metadata
240         NodeMetadata *meta = getmeta(ref, true);
241         // Set fields
242         lua_getfield(L, base, "fields");
243         int fieldstable = lua_gettop(L);
244         lua_pushnil(L);
245         while(lua_next(L, fieldstable) != 0){
246                 // key at index -2 and value at index -1
247                 std::string name = lua_tostring(L, -2);
248                 size_t cl;
249                 const char *cs = lua_tolstring(L, -1, &cl);
250                 std::string value(cs, cl);
251                 meta->setString(name, value);
252                 lua_pop(L, 1); // removes value, keeps key for next iteration
253         }
254         // Set inventory
255         Inventory *inv = meta->getInventory();
256         lua_getfield(L, base, "inventory");
257         int inventorytable = lua_gettop(L);
258         lua_pushnil(L);
259         while(lua_next(L, inventorytable) != 0){
260                 // key at index -2 and value at index -1
261                 std::string name = lua_tostring(L, -2);
262                 inventory_set_list_from_lua(inv, name.c_str(), L, -1);
263                 lua_pop(L, 1); // removes value, keeps key for next iteration
264         }
265         reportMetadataChange(ref);
266         lua_pushboolean(L, true);
267         return 1;
268 }
269
270
271 NodeMetaRef::NodeMetaRef(v3s16 p, ServerEnvironment *env):
272         m_p(p),
273         m_env(env)
274 {
275 }
276
277 NodeMetaRef::~NodeMetaRef()
278 {
279 }
280
281 // Creates an NodeMetaRef and leaves it on top of stack
282 // Not callable from Lua; all references are created on the C side.
283 void NodeMetaRef::create(lua_State *L, v3s16 p, ServerEnvironment *env)
284 {
285         NodeMetaRef *o = new NodeMetaRef(p, env);
286         //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
287         *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
288         luaL_getmetatable(L, className);
289         lua_setmetatable(L, -2);
290 }
291
292 void NodeMetaRef::Register(lua_State *L)
293 {
294         lua_newtable(L);
295         int methodtable = lua_gettop(L);
296         luaL_newmetatable(L, className);
297         int metatable = lua_gettop(L);
298
299         lua_pushliteral(L, "__metatable");
300         lua_pushvalue(L, methodtable);
301         lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
302
303         lua_pushliteral(L, "__index");
304         lua_pushvalue(L, methodtable);
305         lua_settable(L, metatable);
306
307         lua_pushliteral(L, "__gc");
308         lua_pushcfunction(L, gc_object);
309         lua_settable(L, metatable);
310
311         lua_pop(L, 1);  // drop metatable
312
313         luaL_openlib(L, 0, methods, 0);  // fill methodtable
314         lua_pop(L, 1);  // drop methodtable
315
316         // Cannot be created from Lua
317         //lua_register(L, className, create_object);
318 }
319
320 const char NodeMetaRef::className[] = "NodeMetaRef";
321 const luaL_reg NodeMetaRef::methods[] = {
322         luamethod(NodeMetaRef, get_string),
323         luamethod(NodeMetaRef, set_string),
324         luamethod(NodeMetaRef, get_int),
325         luamethod(NodeMetaRef, set_int),
326         luamethod(NodeMetaRef, get_float),
327         luamethod(NodeMetaRef, set_float),
328         luamethod(NodeMetaRef, get_inventory),
329         luamethod(NodeMetaRef, to_table),
330         luamethod(NodeMetaRef, from_table),
331         {0,0}
332 };
333
334 /*
335         Node metadata inventory callbacks
336 */
337
338 // Return number of accepted items to be moved
339 int scriptapi_nodemeta_inventory_allow_move(lua_State *L, v3s16 p,
340                 const std::string &from_list, int from_index,
341                 const std::string &to_list, int to_index,
342                 int count, ServerActiveObject *player)
343 {
344         realitycheck(L);
345         assert(lua_checkstack(L, 20));
346         StackUnroller stack_unroller(L);
347
348         INodeDefManager *ndef = get_server(L)->ndef();
349
350         // If node doesn't exist, we don't know what callback to call
351         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
352         if(node.getContent() == CONTENT_IGNORE)
353                 return 0;
354
355         // Push callback function on stack
356         if(!get_item_callback(L, ndef->get(node).name.c_str(),
357                         "allow_metadata_inventory_move"))
358                 return count;
359
360         // function(pos, from_list, from_index, to_list, to_index, count, player)
361         // pos
362         push_v3s16(L, p);
363         // from_list
364         lua_pushstring(L, from_list.c_str());
365         // from_index
366         lua_pushinteger(L, from_index + 1);
367         // to_list
368         lua_pushstring(L, to_list.c_str());
369         // to_index
370         lua_pushinteger(L, to_index + 1);
371         // count
372         lua_pushinteger(L, count);
373         // player
374         objectref_get_or_create(L, player);
375         if(lua_pcall(L, 7, 1, 0))
376                 script_error(L, "error: %s", lua_tostring(L, -1));
377         if(!lua_isnumber(L, -1))
378                 throw LuaError(L, "allow_metadata_inventory_move should return a number");
379         return luaL_checkinteger(L, -1);
380 }
381
382 // Return number of accepted items to be put
383 int scriptapi_nodemeta_inventory_allow_put(lua_State *L, v3s16 p,
384                 const std::string &listname, int index, ItemStack &stack,
385                 ServerActiveObject *player)
386 {
387         realitycheck(L);
388         assert(lua_checkstack(L, 20));
389         StackUnroller stack_unroller(L);
390
391         INodeDefManager *ndef = get_server(L)->ndef();
392
393         // If node doesn't exist, we don't know what callback to call
394         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
395         if(node.getContent() == CONTENT_IGNORE)
396                 return 0;
397
398         // Push callback function on stack
399         if(!get_item_callback(L, ndef->get(node).name.c_str(),
400                         "allow_metadata_inventory_put"))
401                 return stack.count;
402
403         // Call function(pos, listname, index, stack, player)
404         // pos
405         push_v3s16(L, p);
406         // listname
407         lua_pushstring(L, listname.c_str());
408         // index
409         lua_pushinteger(L, index + 1);
410         // stack
411         LuaItemStack::create(L, stack);
412         // player
413         objectref_get_or_create(L, player);
414         if(lua_pcall(L, 5, 1, 0))
415                 script_error(L, "error: %s", lua_tostring(L, -1));
416         if(!lua_isnumber(L, -1))
417                 throw LuaError(L, "allow_metadata_inventory_put should return a number");
418         return luaL_checkinteger(L, -1);
419 }
420
421 // Return number of accepted items to be taken
422 int scriptapi_nodemeta_inventory_allow_take(lua_State *L, v3s16 p,
423                 const std::string &listname, int index, ItemStack &stack,
424                 ServerActiveObject *player)
425 {
426         realitycheck(L);
427         assert(lua_checkstack(L, 20));
428         StackUnroller stack_unroller(L);
429
430         INodeDefManager *ndef = get_server(L)->ndef();
431
432         // If node doesn't exist, we don't know what callback to call
433         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
434         if(node.getContent() == CONTENT_IGNORE)
435                 return 0;
436
437         // Push callback function on stack
438         if(!get_item_callback(L, ndef->get(node).name.c_str(),
439                         "allow_metadata_inventory_take"))
440                 return stack.count;
441
442         // Call function(pos, listname, index, count, player)
443         // pos
444         push_v3s16(L, p);
445         // listname
446         lua_pushstring(L, listname.c_str());
447         // index
448         lua_pushinteger(L, index + 1);
449         // stack
450         LuaItemStack::create(L, stack);
451         // player
452         objectref_get_or_create(L, player);
453         if(lua_pcall(L, 5, 1, 0))
454                 script_error(L, "error: %s", lua_tostring(L, -1));
455         if(!lua_isnumber(L, -1))
456                 throw LuaError(L, "allow_metadata_inventory_take should return a number");
457         return luaL_checkinteger(L, -1);
458 }
459
460 // Report moved items
461 void scriptapi_nodemeta_inventory_on_move(lua_State *L, v3s16 p,
462                 const std::string &from_list, int from_index,
463                 const std::string &to_list, int to_index,
464                 int count, ServerActiveObject *player)
465 {
466         realitycheck(L);
467         assert(lua_checkstack(L, 20));
468         StackUnroller stack_unroller(L);
469
470         INodeDefManager *ndef = get_server(L)->ndef();
471
472         // If node doesn't exist, we don't know what callback to call
473         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
474         if(node.getContent() == CONTENT_IGNORE)
475                 return;
476
477         // Push callback function on stack
478         if(!get_item_callback(L, ndef->get(node).name.c_str(),
479                         "on_metadata_inventory_move"))
480                 return;
481
482         // function(pos, from_list, from_index, to_list, to_index, count, player)
483         // pos
484         push_v3s16(L, p);
485         // from_list
486         lua_pushstring(L, from_list.c_str());
487         // from_index
488         lua_pushinteger(L, from_index + 1);
489         // to_list
490         lua_pushstring(L, to_list.c_str());
491         // to_index
492         lua_pushinteger(L, to_index + 1);
493         // count
494         lua_pushinteger(L, count);
495         // player
496         objectref_get_or_create(L, player);
497         if(lua_pcall(L, 7, 0, 0))
498                 script_error(L, "error: %s", lua_tostring(L, -1));
499 }
500
501 // Report put items
502 void scriptapi_nodemeta_inventory_on_put(lua_State *L, v3s16 p,
503                 const std::string &listname, int index, ItemStack &stack,
504                 ServerActiveObject *player)
505 {
506         realitycheck(L);
507         assert(lua_checkstack(L, 20));
508         StackUnroller stack_unroller(L);
509
510         INodeDefManager *ndef = get_server(L)->ndef();
511
512         // If node doesn't exist, we don't know what callback to call
513         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
514         if(node.getContent() == CONTENT_IGNORE)
515                 return;
516
517         // Push callback function on stack
518         if(!get_item_callback(L, ndef->get(node).name.c_str(),
519                         "on_metadata_inventory_put"))
520                 return;
521
522         // Call function(pos, listname, index, stack, player)
523         // pos
524         push_v3s16(L, p);
525         // listname
526         lua_pushstring(L, listname.c_str());
527         // index
528         lua_pushinteger(L, index + 1);
529         // stack
530         LuaItemStack::create(L, stack);
531         // player
532         objectref_get_or_create(L, player);
533         if(lua_pcall(L, 5, 0, 0))
534                 script_error(L, "error: %s", lua_tostring(L, -1));
535 }
536
537 // Report taken items
538 void scriptapi_nodemeta_inventory_on_take(lua_State *L, v3s16 p,
539                 const std::string &listname, int index, ItemStack &stack,
540                 ServerActiveObject *player)
541 {
542         realitycheck(L);
543         assert(lua_checkstack(L, 20));
544         StackUnroller stack_unroller(L);
545
546         INodeDefManager *ndef = get_server(L)->ndef();
547
548         // If node doesn't exist, we don't know what callback to call
549         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
550         if(node.getContent() == CONTENT_IGNORE)
551                 return;
552
553         // Push callback function on stack
554         if(!get_item_callback(L, ndef->get(node).name.c_str(),
555                         "on_metadata_inventory_take"))
556                 return;
557
558         // Call function(pos, listname, index, stack, player)
559         // pos
560         push_v3s16(L, p);
561         // listname
562         lua_pushstring(L, listname.c_str());
563         // index
564         lua_pushinteger(L, index + 1);
565         // stack
566         LuaItemStack::create(L, stack);
567         // player
568         objectref_get_or_create(L, player);
569         if(lua_pcall(L, 5, 0, 0))
570                 script_error(L, "error: %s", lua_tostring(L, -1));
571 }