1 /*
2 itemdef.cpp
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4 Copyright (C) 2013 Kahrl <kahrl@gmx.net>
5 */
6
7 /*
8 This file is part of Freeminer.
9
10 Freeminer is free software: you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation, either version 3 of the License, or
13 (at your option) any later version.
14
15 Freeminer is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with Freeminer. If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "itemdef.h"
25
26 #include "gamedef.h"
27 #include "nodedef.h"
28 #include "tool.h"
29 #include "inventory.h"
30 #ifndef SERVER
31 #include "mapblock_mesh.h"
32 #include "mesh.h"
33 #include "wieldmesh.h"
34 #include "tile.h"
35 #include "clientmap.h"
36 #include "mapblock.h"
37 #endif
38 #include "log.h"
39 #include "main.h" // g_settings
40 #include "settings.h"
41 #include "util/serialize.h"
42 #include "util/container.h"
43 #include "util/thread.h"
44 #include <map>
45 #include <set>
46
47 #ifdef __ANDROID__
48 #include <GLES/gl.h>
49 #endif
50
51 /*
52 ItemDefinition
53 */
ItemDefinition()54 ItemDefinition::ItemDefinition()
55 {
56 resetInitial();
57 }
58
ItemDefinition(const ItemDefinition & def)59 ItemDefinition::ItemDefinition(const ItemDefinition &def)
60 {
61 resetInitial();
62 *this = def;
63 }
64
operator =(const ItemDefinition & def)65 ItemDefinition& ItemDefinition::operator=(const ItemDefinition &def)
66 {
67 if(this == &def)
68 return *this;
69
70 reset();
71
72 type = def.type;
73 name = def.name;
74 description = def.description;
75 inventory_image = def.inventory_image;
76 wield_image = def.wield_image;
77 wield_scale = def.wield_scale;
78 stack_max = def.stack_max;
79 usable = def.usable;
80 liquids_pointable = def.liquids_pointable;
81 if(def.tool_capabilities)
82 {
83 tool_capabilities = new ToolCapabilities(
84 *def.tool_capabilities);
85 }
86 groups = def.groups;
87 node_placement_prediction = def.node_placement_prediction;
88 sound_place = def.sound_place;
89 range = def.range;
90 return *this;
91 }
92
~ItemDefinition()93 ItemDefinition::~ItemDefinition()
94 {
95 reset();
96 }
97
resetInitial()98 void ItemDefinition::resetInitial()
99 {
100 // Initialize pointers to NULL so reset() does not delete undefined pointers
101 tool_capabilities = NULL;
102 reset();
103 }
104
reset()105 void ItemDefinition::reset()
106 {
107 type = ITEM_NONE;
108 name = "";
109 description = "";
110 inventory_image = "";
111 wield_image = "";
112 wield_scale = v3f(1.0, 1.0, 1.0);
113 stack_max = 99;
114 usable = false;
115 liquids_pointable = false;
116 if(tool_capabilities)
117 {
118 delete tool_capabilities;
119 tool_capabilities = NULL;
120 }
121 groups.clear();
122 sound_place = SimpleSoundSpec();
123 range = -1;
124
125 node_placement_prediction = "";
126 }
127
serialize(std::ostream & os,u16 protocol_version) const128 void ItemDefinition::serialize(std::ostream &os, u16 protocol_version) const
129 {
130 if(protocol_version <= 17)
131 writeU8(os, 1); // version
132 else if(protocol_version <= 20)
133 writeU8(os, 2); // version
134 else
135 writeU8(os, 3); // version
136 writeU8(os, type);
137 os<<serializeString(name);
138 os<<serializeString(description);
139 os<<serializeString(inventory_image);
140 os<<serializeString(wield_image);
141 writeV3F1000(os, wield_scale);
142 writeS16(os, stack_max);
143 writeU8(os, usable);
144 writeU8(os, liquids_pointable);
145 std::string tool_capabilities_s = "";
146 if(tool_capabilities){
147 std::ostringstream tmp_os(std::ios::binary);
148 tool_capabilities->serialize(tmp_os, protocol_version);
149 tool_capabilities_s = tmp_os.str();
150 }
151 os<<serializeString(tool_capabilities_s);
152 writeU16(os, groups.size());
153 for(std::map<std::string, int>::const_iterator
154 i = groups.begin(); i != groups.end(); i++){
155 os<<serializeString(i->first);
156 writeS16(os, i->second);
157 }
158 os<<serializeString(node_placement_prediction);
159 if(protocol_version > 17){
160 //serializeSimpleSoundSpec(sound_place, os);
161 os<<serializeString(sound_place.name);
162 writeF1000(os, sound_place.gain);
163 }
164 if(protocol_version > 20){
165 writeF1000(os, range);
166 }
167 }
168
deSerialize(std::istream & is)169 void ItemDefinition::deSerialize(std::istream &is)
170 {
171 // Reset everything
172 reset();
173
174 // Deserialize
175 int version = readU8(is);
176 if(version < 1 || version > 3)
177 throw SerializationError("unsupported ItemDefinition version");
178 type = (enum ItemType)readU8(is);
179 name = deSerializeString(is);
180 description = deSerializeString(is);
181 inventory_image = deSerializeString(is);
182 wield_image = deSerializeString(is);
183 wield_scale = readV3F1000(is);
184 stack_max = readS16(is);
185 usable = readU8(is);
186 liquids_pointable = readU8(is);
187 std::string tool_capabilities_s = deSerializeString(is);
188 if(!tool_capabilities_s.empty())
189 {
190 std::istringstream tmp_is(tool_capabilities_s, std::ios::binary);
191 tool_capabilities = new ToolCapabilities;
192 tool_capabilities->deSerialize(tmp_is);
193 }
194 groups.clear();
195 u32 groups_size = readU16(is);
196 for(u32 i=0; i<groups_size; i++){
197 std::string name = deSerializeString(is);
198 int value = readS16(is);
199 groups[name] = value;
200 }
201 if(version == 1){
202 // We cant be sure that node_placement_prediction is send in version 1
203 try{
204 node_placement_prediction = deSerializeString(is);
205 }catch(SerializationError &e) {};
206 // Set the old default sound
207 sound_place.name = "default_place_node";
208 sound_place.gain = 0.5;
209 } else if(version >= 2) {
210 node_placement_prediction = deSerializeString(is);
211 //deserializeSimpleSoundSpec(sound_place, is);
212 sound_place.name = deSerializeString(is);
213 sound_place.gain = readF1000(is);
214 }
215 if(version == 3) {
216 range = readF1000(is);
217 }
218 // If you add anything here, insert it primarily inside the try-catch
219 // block to not need to increase the version.
220 try{
221 }catch(SerializationError &e) {};
222 }
223
224 /*
225 CItemDefManager
226 */
227
228 // SUGG: Support chains of aliases?
229
230 class CItemDefManager: public IWritableItemDefManager
231 {
232 #ifndef SERVER
233 struct ClientCached
234 {
235 video::ITexture *inventory_texture;
236 scene::IMesh *wield_mesh;
237
ClientCachedCItemDefManager::ClientCached238 ClientCached():
239 inventory_texture(NULL),
240 wield_mesh(NULL)
241 {}
242 };
243 #endif
244
245 public:
CItemDefManager()246 CItemDefManager()
247 {
248
249 #ifndef SERVER
250 m_main_thread = get_current_thread_id();
251 #endif
252 clear();
253 }
~CItemDefManager()254 virtual ~CItemDefManager()
255 {
256 #ifndef SERVER
257 const std::list<ClientCached*> &values = m_clientcached.getValues();
258 for(std::list<ClientCached*>::const_iterator
259 i = values.begin(); i != values.end(); ++i)
260 {
261 ClientCached *cc = *i;
262 if (cc->wield_mesh)
263 cc->wield_mesh->drop();
264 delete cc;
265 }
266
267 #endif
268 for (std::map<std::string, ItemDefinition*>::iterator iter =
269 m_item_definitions.begin(); iter != m_item_definitions.end();
270 iter ++) {
271 delete iter->second;
272 }
273 m_item_definitions.clear();
274 }
get(const std::string & name_) const275 virtual const ItemDefinition& get(const std::string &name_) const
276 {
277 // Convert name according to possible alias
278 std::string name = getAlias(name_);
279 // Get the definition
280 std::map<std::string, ItemDefinition*>::const_iterator i;
281 i = m_item_definitions.find(name);
282 if(i == m_item_definitions.end())
283 i = m_item_definitions.find("unknown");
284 assert(i != m_item_definitions.end());
285 return *(i->second);
286 }
getAlias(const std::string & name) const287 virtual std::string getAlias(const std::string &name) const
288 {
289 std::map<std::string, std::string>::const_iterator i;
290 i = m_aliases.find(name);
291 if(i != m_aliases.end())
292 return i->second;
293 return name;
294 }
getAll() const295 virtual std::set<std::string> getAll() const
296 {
297 std::set<std::string> result;
298 for(std::map<std::string, ItemDefinition*>::const_iterator
299 i = m_item_definitions.begin();
300 i != m_item_definitions.end(); i++)
301 {
302 result.insert(i->first);
303 }
304 for(std::map<std::string, std::string>::const_iterator
305 i = m_aliases.begin();
306 i != m_aliases.end(); i++)
307 {
308 result.insert(i->first);
309 }
310 return result;
311 }
isKnown(const std::string & name_) const312 virtual bool isKnown(const std::string &name_) const
313 {
314 // Convert name according to possible alias
315 std::string name = getAlias(name_);
316 // Get the definition
317 std::map<std::string, ItemDefinition*>::const_iterator i;
318 return m_item_definitions.find(name) != m_item_definitions.end();
319 }
320 #ifndef SERVER
321 public:
createClientCachedDirect(const std::string & name,IGameDef * gamedef) const322 ClientCached* createClientCachedDirect(const std::string &name,
323 IGameDef *gamedef) const
324 {
325 infostream<<"Lazily creating item texture and mesh for \""
326 <<name<<"\""<<std::endl;
327
328 // This is not thread-safe
329 assert(get_current_thread_id() == m_main_thread);
330
331 // Skip if already in cache
332 ClientCached *cc = NULL;
333 m_clientcached.get(name, &cc);
334 if(cc)
335 return cc;
336
337 ITextureSource *tsrc = gamedef->getTextureSource();
338 INodeDefManager *nodedef = gamedef->getNodeDefManager();
339 const ItemDefinition &def = get(name);
340
341 // Create new ClientCached
342 cc = new ClientCached();
343
344 // Create an inventory texture
345 cc->inventory_texture = NULL;
346 if(def.inventory_image != "")
347 cc->inventory_texture = tsrc->getTexture(def.inventory_image);
348
349 // Additional processing for nodes:
350 // - Create a wield mesh if WieldMeshSceneNode can't render
351 // the node on its own.
352 // - If inventory_texture isn't set yet, create one using
353 // render-to-texture.
354 if (def.type == ITEM_NODE) {
355 // Get node properties
356 content_t id = nodedef->getId(name);
357 const ContentFeatures &f = nodedef->get(id);
358
359 bool need_rtt_mesh = cc->inventory_texture == NULL;
360
361 // Keep this in sync with WieldMeshSceneNode::setItem()
362 bool need_wield_mesh =
363 !(f.mesh_ptr[0] ||
364 f.drawtype == NDT_NORMAL ||
365 f.drawtype == NDT_ALLFACES ||
366 f.drawtype == NDT_AIRLIKE);
367
368 scene::IMesh *node_mesh = NULL;
369
370 bool reenable_shaders = false;
371
372 if (need_rtt_mesh || need_wield_mesh) {
373 u8 param1 = 0;
374 if (f.param_type == CPT_LIGHT)
375 param1 = 0xee;
376
377 /*
378 Make a mesh from the node
379 */
380 if (g_settings->getBool("enable_shaders")) {
381 reenable_shaders = true;
382 g_settings->setBool("enable_shaders", false);
383 }
384 Map map(gamedef);
385 MapDrawControl map_draw_control;
386 MeshMakeData mesh_make_data(gamedef, map, map_draw_control);
387 v3s16 p0(0, 0, 0);
388 auto block = map.createBlankBlockNoInsert(p0);
389 auto air_node = MapNode(CONTENT_AIR, LIGHT_MAX);
390 for(s16 z0=0; z0<=2; ++z0)
391 for(s16 y0=0; y0<=2; ++y0)
392 for(s16 x0=0; x0<=2; ++x0) {
393 v3s16 p(x0,y0,z0);
394 block->setNode(p, air_node);
395 }
396 u8 param2 = 0;
397 if (f.param_type_2 == CPT2_WALLMOUNTED)
398 param2 = 1;
399 MapNode mesh_make_node(id, param1, param2);
400 mesh_make_data.fillSingleNode(&mesh_make_node);
401 block->setNode(v3s16(1,1,1), mesh_make_node);
402 map.insertBlock(block);
403 MapBlockMesh mapblock_mesh(&mesh_make_data, v3s16(0, 0, 0));
404
405 /* MT
406 MeshMakeData mesh_make_data(gamedef);
407 u8 param2 = 0;
408 if (f.param_type_2 == CPT2_WALLMOUNTED)
409 param2 = 1;
410 MapNode mesh_make_node(id, param1, param2);
411 mesh_make_data.fillSingleNode(&mesh_make_node);
412 MapBlockMesh mapblock_mesh(&mesh_make_data, v3s16(0, 0, 0));
413 */
414
415 node_mesh = mapblock_mesh.getMesh();
416 node_mesh->grab();
417 video::SColor c(255, 255, 255, 255);
418 setMeshColor(node_mesh, c);
419
420 // scale and translate the mesh so it's a
421 // unit cube centered on the origin
422 scaleMesh(node_mesh, v3f(1.0/BS, 1.0/BS, 1.0/BS));
423 translateMesh(node_mesh, v3f(-1.0, -1.0, -1.0));
424 }
425
426 /*
427 Draw node mesh into a render target texture
428 */
429 if (need_rtt_mesh) {
430 TextureFromMeshParams params;
431 params.mesh = node_mesh;
432 params.dim.set(64, 64);
433 params.rtt_texture_name = "INVENTORY_"
434 + def.name + "_RTT";
435 params.delete_texture_on_shutdown = true;
436 params.camera_position.set(0, 1.0, -1.5);
437 params.camera_position.rotateXZBy(45);
438 params.camera_lookat.set(0, 0, 0);
439 // Set orthogonal projection
440 params.camera_projection_matrix.buildProjectionMatrixOrthoLH(
441 1.65, 1.65, 0, 100);
442 params.ambient_light.set(1.0, 0.2, 0.2, 0.2);
443 params.light_position.set(10, 100, -50);
444 params.light_color.set(1.0, 0.5, 0.5, 0.5);
445 params.light_radius = 1000;
446
447 #ifdef __ANDROID__
448 params.camera_position.set(0, -1.0, -1.5);
449 params.camera_position.rotateXZBy(45);
450 params.light_position.set(10, -100, -50);
451 #endif
452 cc->inventory_texture =
453 tsrc->generateTextureFromMesh(params);
454
455 // render-to-target didn't work
456 if (cc->inventory_texture == NULL) {
457 cc->inventory_texture =
458 tsrc->getTexture(f.tiledef[0].name);
459 }
460 }
461
462 /*
463 Use the node mesh as the wield mesh
464 */
465 if (need_wield_mesh) {
466 cc->wield_mesh = node_mesh;
467 cc->wield_mesh->grab();
468
469 // no way reference count can be smaller than 2 in this place!
470 assert(cc->wield_mesh->getReferenceCount() >= 2);
471 }
472
473 if (node_mesh)
474 node_mesh->drop();
475
476 if (reenable_shaders)
477 g_settings->setBool("enable_shaders",true);
478 }
479
480 // Put in cache
481 m_clientcached.set(name, cc);
482
483 return cc;
484 }
getClientCached(const std::string & name,IGameDef * gamedef) const485 ClientCached* getClientCached(const std::string &name,
486 IGameDef *gamedef) const
487 {
488 ClientCached *cc = NULL;
489 m_clientcached.get(name, &cc);
490 if(cc)
491 return cc;
492
493 if(get_current_thread_id() == m_main_thread)
494 {
495 return createClientCachedDirect(name, gamedef);
496 }
497 else
498 {
499 // We're gonna ask the result to be put into here
500 static ResultQueue<std::string, ClientCached*, u8, u8> result_queue;
501
502 // Throw a request in
503 m_get_clientcached_queue.add(name, 0, 0, &result_queue);
504 try{
505 while(true) {
506 // Wait result for a second
507 GetResult<std::string, ClientCached*, u8, u8>
508 result = result_queue.pop_front(1000);
509
510 if (result.key == name) {
511 return result.item;
512 }
513 }
514 }
515 catch(ItemNotFoundException &e)
516 {
517 errorstream<<"Waiting for clientcached " << name << " timed out."<<std::endl;
518 return &m_dummy_clientcached;
519 }
520 }
521 }
522 // Get item inventory texture
getInventoryTexture(const std::string & name,IGameDef * gamedef) const523 virtual video::ITexture* getInventoryTexture(const std::string &name,
524 IGameDef *gamedef) const
525 {
526 ClientCached *cc = getClientCached(name, gamedef);
527 if(!cc)
528 return NULL;
529 return cc->inventory_texture;
530 }
531 // Get item wield mesh
getWieldMesh(const std::string & name,IGameDef * gamedef) const532 virtual scene::IMesh* getWieldMesh(const std::string &name,
533 IGameDef *gamedef) const
534 {
535 ClientCached *cc = getClientCached(name, gamedef);
536 if(!cc)
537 return NULL;
538 return cc->wield_mesh;
539 }
540 #endif
clear()541 void clear()
542 {
543 for(std::map<std::string, ItemDefinition*>::const_iterator
544 i = m_item_definitions.begin();
545 i != m_item_definitions.end(); i++)
546 {
547 delete i->second;
548 }
549 m_item_definitions.clear();
550 m_aliases.clear();
551
552 // Add the four builtin items:
553 // "" is the hand
554 // "unknown" is returned whenever an undefined item
555 // is accessed (is also the unknown node)
556 // "air" is the air node
557 // "ignore" is the ignore node
558
559 ItemDefinition* hand_def = new ItemDefinition;
560 hand_def->name = "";
561 hand_def->wield_image = "wieldhand.png";
562 hand_def->tool_capabilities = new ToolCapabilities;
563 m_item_definitions.insert(std::make_pair("", hand_def));
564
565 ItemDefinition* unknown_def = new ItemDefinition;
566 unknown_def->type = ITEM_NODE;
567 unknown_def->name = "unknown";
568 m_item_definitions.insert(std::make_pair("unknown", unknown_def));
569
570 ItemDefinition* air_def = new ItemDefinition;
571 air_def->type = ITEM_NODE;
572 air_def->name = "air";
573 m_item_definitions.insert(std::make_pair("air", air_def));
574
575 ItemDefinition* ignore_def = new ItemDefinition;
576 ignore_def->type = ITEM_NODE;
577 ignore_def->name = "ignore";
578 m_item_definitions.insert(std::make_pair("ignore", ignore_def));
579 }
registerItem(const ItemDefinition & def)580 virtual void registerItem(const ItemDefinition &def)
581 {
582 verbosestream<<"ItemDefManager: registering \""<<def.name<<"\""<<std::endl;
583 // Ensure that the "" item (the hand) always has ToolCapabilities
584 if(def.name == "")
585 assert(def.tool_capabilities != NULL);
586
587 if(m_item_definitions.count(def.name) == 0)
588 m_item_definitions[def.name] = new ItemDefinition(def);
589 else
590 *(m_item_definitions[def.name]) = def;
591
592 // Remove conflicting alias if it exists
593 bool alias_removed = (m_aliases.erase(def.name) != 0);
594 if(alias_removed)
595 infostream<<"ItemDefManager: erased alias "<<def.name
596 <<" because item was defined"<<std::endl;
597 }
registerAlias(const std::string & name,const std::string & convert_to)598 virtual void registerAlias(const std::string &name,
599 const std::string &convert_to)
600 {
601 if(m_item_definitions.find(name) == m_item_definitions.end())
602 {
603 verbosestream<<"ItemDefManager: setting alias "<<name
604 <<" -> "<<convert_to<<std::endl;
605 m_aliases[name] = convert_to;
606 }
607 }
serialize(std::ostream & os,u16 protocol_version)608 void serialize(std::ostream &os, u16 protocol_version)
609 {
610 writeU8(os, 0); // version
611 u16 count = m_item_definitions.size();
612 writeU16(os, count);
613 for(std::map<std::string, ItemDefinition*>::const_iterator
614 i = m_item_definitions.begin();
615 i != m_item_definitions.end(); i++)
616 {
617 ItemDefinition *def = i->second;
618 // Serialize ItemDefinition and write wrapped in a string
619 std::ostringstream tmp_os(std::ios::binary);
620 def->serialize(tmp_os, protocol_version);
621 os<<serializeString(tmp_os.str());
622 }
623 writeU16(os, m_aliases.size());
624 for(std::map<std::string, std::string>::const_iterator
625 i = m_aliases.begin(); i != m_aliases.end(); i++)
626 {
627 os<<serializeString(i->first);
628 os<<serializeString(i->second);
629 }
630 }
deSerialize(std::istream & is)631 void deSerialize(std::istream &is)
632 {
633 // Clear everything
634 clear();
635 // Deserialize
636 int version = readU8(is);
637 if(version != 0)
638 throw SerializationError("unsupported ItemDefManager version");
639 u16 count = readU16(is);
640 for(u16 i=0; i<count; i++)
641 {
642 // Deserialize a string and grab an ItemDefinition from it
643 std::istringstream tmp_is(deSerializeString(is), std::ios::binary);
644 ItemDefinition def;
645 def.deSerialize(tmp_is);
646 // Register
647 registerItem(def);
648 }
649 u16 num_aliases = readU16(is);
650 for(u16 i=0; i<num_aliases; i++)
651 {
652 std::string name = deSerializeString(is);
653 std::string convert_to = deSerializeString(is);
654 registerAlias(name, convert_to);
655 }
656 }
processQueue(IGameDef * gamedef)657 void processQueue(IGameDef *gamedef)
658 {
659 #ifndef SERVER
660 //NOTE this is only thread safe for ONE consumer thread!
661 while(!m_get_clientcached_queue.empty())
662 {
663 GetRequest<std::string, ClientCached*, u8, u8>
664 request = m_get_clientcached_queue.pop();
665
666 m_get_clientcached_queue.pushResult(request,
667 createClientCachedDirect(request.key, gamedef));
668 }
669 #endif
670 }
671 private:
672 // Key is name
673 std::map<std::string, ItemDefinition*> m_item_definitions;
674 // Aliases
675 std::map<std::string, std::string> m_aliases;
676 #ifndef SERVER
677 // The id of the thread that is allowed to use irrlicht directly
678 threadid_t m_main_thread;
679 // A reference to this can be returned when nothing is found, to avoid NULLs
680 mutable ClientCached m_dummy_clientcached;
681 // Cached textures and meshes
682 mutable MutexedMap<std::string, ClientCached*> m_clientcached;
683 // Queued clientcached fetches (to be processed by the main thread)
684 mutable RequestQueue<std::string, ClientCached*, u8, u8> m_get_clientcached_queue;
685 #endif
686 };
687
createItemDefManager()688 IWritableItemDefManager* createItemDefManager()
689 {
690 return new CItemDefManager();
691 }
692