3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4 Copyright (C) 2013 Kahrl <kahrl@gmx.net>
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License along
17 with this program; if not, write to the Free Software Foundation, Inc.,
18 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 #include "inventory.h"
28 #include "mapblock_mesh.h"
33 #include "main.h" // g_settings
35 #include "util/serialize.h"
36 #include "util/container.h"
37 #include "util/thread.h"
44 ItemDefinition::ItemDefinition()
49 ItemDefinition::ItemDefinition(const ItemDefinition &def)
55 ItemDefinition& ItemDefinition::operator=(const ItemDefinition &def)
64 description = def.description;
65 inventory_image = def.inventory_image;
66 wield_image = def.wield_image;
67 wield_scale = def.wield_scale;
68 stack_max = def.stack_max;
70 liquids_pointable = def.liquids_pointable;
71 if(def.tool_capabilities)
73 tool_capabilities = new ToolCapabilities(
74 *def.tool_capabilities);
77 node_placement_prediction = def.node_placement_prediction;
78 sound_place = def.sound_place;
83 ItemDefinition::~ItemDefinition()
88 void ItemDefinition::resetInitial()
90 // Initialize pointers to NULL so reset() does not delete undefined pointers
91 tool_capabilities = NULL;
95 void ItemDefinition::reset()
100 inventory_image = "";
102 wield_scale = v3f(1.0, 1.0, 1.0);
105 liquids_pointable = false;
106 if(tool_capabilities)
108 delete tool_capabilities;
109 tool_capabilities = NULL;
112 sound_place = SimpleSoundSpec();
115 node_placement_prediction = "";
118 void ItemDefinition::serialize(std::ostream &os, u16 protocol_version) const
120 if(protocol_version <= 17)
121 writeU8(os, 1); // version
122 else if(protocol_version <= 20)
123 writeU8(os, 2); // version
125 writeU8(os, 3); // version
127 os<<serializeString(name);
128 os<<serializeString(description);
129 os<<serializeString(inventory_image);
130 os<<serializeString(wield_image);
131 writeV3F1000(os, wield_scale);
132 writeS16(os, stack_max);
134 writeU8(os, liquids_pointable);
135 std::string tool_capabilities_s = "";
136 if(tool_capabilities){
137 std::ostringstream tmp_os(std::ios::binary);
138 tool_capabilities->serialize(tmp_os, protocol_version);
139 tool_capabilities_s = tmp_os.str();
141 os<<serializeString(tool_capabilities_s);
142 writeU16(os, groups.size());
143 for(std::map<std::string, int>::const_iterator
144 i = groups.begin(); i != groups.end(); i++){
145 os<<serializeString(i->first);
146 writeS16(os, i->second);
148 os<<serializeString(node_placement_prediction);
149 if(protocol_version > 17){
150 //serializeSimpleSoundSpec(sound_place, os);
151 os<<serializeString(sound_place.name);
152 writeF1000(os, sound_place.gain);
154 if(protocol_version > 20){
155 writeF1000(os, range);
159 void ItemDefinition::deSerialize(std::istream &is)
165 int version = readU8(is);
166 if(version < 1 || version > 3)
167 throw SerializationError("unsupported ItemDefinition version");
168 type = (enum ItemType)readU8(is);
169 name = deSerializeString(is);
170 description = deSerializeString(is);
171 inventory_image = deSerializeString(is);
172 wield_image = deSerializeString(is);
173 wield_scale = readV3F1000(is);
174 stack_max = readS16(is);
176 liquids_pointable = readU8(is);
177 std::string tool_capabilities_s = deSerializeString(is);
178 if(!tool_capabilities_s.empty())
180 std::istringstream tmp_is(tool_capabilities_s, std::ios::binary);
181 tool_capabilities = new ToolCapabilities;
182 tool_capabilities->deSerialize(tmp_is);
185 u32 groups_size = readU16(is);
186 for(u32 i=0; i<groups_size; i++){
187 std::string name = deSerializeString(is);
188 int value = readS16(is);
189 groups[name] = value;
192 // We cant be sure that node_placement_prediction is send in version 1
194 node_placement_prediction = deSerializeString(is);
195 }catch(SerializationError &e) {};
196 // Set the old default sound
197 sound_place.name = "default_place_node";
198 sound_place.gain = 0.5;
199 } else if(version >= 2) {
200 node_placement_prediction = deSerializeString(is);
201 //deserializeSimpleSoundSpec(sound_place, is);
202 sound_place.name = deSerializeString(is);
203 sound_place.gain = readF1000(is);
206 range = readF1000(is);
208 // If you add anything here, insert it primarily inside the try-catch
209 // block to not need to increase the version.
211 }catch(SerializationError &e) {};
218 // SUGG: Support chains of aliases?
220 class CItemDefManager: public IWritableItemDefManager
225 video::ITexture *inventory_texture;
226 scene::IMesh *wield_mesh;
229 inventory_texture(NULL),
240 m_main_thread = get_current_thread_id();
244 virtual ~CItemDefManager()
247 const std::list<ClientCached*> &values = m_clientcached.getValues();
248 for(std::list<ClientCached*>::const_iterator
249 i = values.begin(); i != values.end(); ++i)
251 ClientCached *cc = *i;
253 cc->wield_mesh->drop();
258 for (std::map<std::string, ItemDefinition*>::iterator iter =
259 m_item_definitions.begin(); iter != m_item_definitions.end();
263 m_item_definitions.clear();
265 virtual const ItemDefinition& get(const std::string &name_) const
267 // Convert name according to possible alias
268 std::string name = getAlias(name_);
269 // Get the definition
270 std::map<std::string, ItemDefinition*>::const_iterator i;
271 i = m_item_definitions.find(name);
272 if(i == m_item_definitions.end())
273 i = m_item_definitions.find("unknown");
274 assert(i != m_item_definitions.end());
277 virtual std::string getAlias(const std::string &name) const
279 std::map<std::string, std::string>::const_iterator i;
280 i = m_aliases.find(name);
281 if(i != m_aliases.end())
285 virtual std::set<std::string> getAll() const
287 std::set<std::string> result;
288 for(std::map<std::string, ItemDefinition*>::const_iterator
289 i = m_item_definitions.begin();
290 i != m_item_definitions.end(); i++)
292 result.insert(i->first);
294 for(std::map<std::string, std::string>::const_iterator
295 i = m_aliases.begin();
296 i != m_aliases.end(); i++)
298 result.insert(i->first);
302 virtual bool isKnown(const std::string &name_) const
304 // Convert name according to possible alias
305 std::string name = getAlias(name_);
306 // Get the definition
307 std::map<std::string, ItemDefinition*>::const_iterator i;
308 return m_item_definitions.find(name) != m_item_definitions.end();
312 ClientCached* createClientCachedDirect(const std::string &name,
313 IGameDef *gamedef) const
315 infostream<<"Lazily creating item texture and mesh for \""
316 <<name<<"\""<<std::endl;
318 // This is not thread-safe
319 assert(get_current_thread_id() == m_main_thread);
321 // Skip if already in cache
322 ClientCached *cc = NULL;
323 m_clientcached.get(name, &cc);
327 ITextureSource *tsrc = gamedef->getTextureSource();
328 INodeDefManager *nodedef = gamedef->getNodeDefManager();
329 IrrlichtDevice *device = tsrc->getDevice();
330 video::IVideoDriver *driver = device->getVideoDriver();
331 const ItemDefinition *def = &get(name);
333 // Create new ClientCached
334 cc = new ClientCached();
336 bool need_node_mesh = false;
338 // Create an inventory texture
339 cc->inventory_texture = NULL;
340 if(def->inventory_image != "")
342 cc->inventory_texture = tsrc->getTexture(def->inventory_image);
344 else if(def->type == ITEM_NODE)
346 need_node_mesh = true;
349 // Create a wield mesh
350 assert(cc->wield_mesh == NULL);
351 if(def->type == ITEM_NODE && def->wield_image == "")
353 need_node_mesh = true;
355 else if(def->wield_image != "" || def->inventory_image != "")
357 // Extrude the wield image into a mesh
359 std::string imagename;
360 if(def->wield_image != "")
361 imagename = def->wield_image;
363 imagename = def->inventory_image;
365 cc->wield_mesh = createExtrudedMesh(
366 tsrc->getTexture(imagename),
368 def->wield_scale * v3f(40.0, 40.0, 4.0));
369 if(cc->wield_mesh == NULL)
371 infostream<<"ItemDefManager: WARNING: "
372 <<"updateTexturesAndMeshes(): "
373 <<"Unable to create extruded mesh for item "
374 <<def->name<<std::endl;
383 content_t id = nodedef->getId(def->name);
384 const ContentFeatures &f = nodedef->get(id);
387 if(f.param_type == CPT_LIGHT)
391 Make a mesh from the node
393 MeshMakeData mesh_make_data(gamedef);
394 MapNode mesh_make_node(id, param1, 0);
395 mesh_make_data.fillSingleNode(&mesh_make_node);
396 MapBlockMesh mapblock_mesh(&mesh_make_data);
398 scene::IMesh *node_mesh = mapblock_mesh.getMesh();
400 video::SColor c(255, 255, 255, 255);
401 if(g_settings->getBool("enable_shaders"))
402 c = MapBlock_LightColor(255, 0xffff, decode_light(f.light_source));
403 setMeshColor(node_mesh, c);
406 Scale and translate the mesh so it's a unit cube
407 centered on the origin
409 scaleMesh(node_mesh, v3f(1.0/BS, 1.0/BS, 1.0/BS));
410 translateMesh(node_mesh, v3f(-1.0, -1.0, -1.0));
413 Draw node mesh into a render target texture
415 if(cc->inventory_texture == NULL)
417 TextureFromMeshParams params;
418 params.mesh = node_mesh;
419 params.dim.set(64, 64);
420 params.rtt_texture_name = "INVENTORY_"
421 + def->name + "_RTT";
422 params.delete_texture_on_shutdown = true;
423 params.camera_position.set(0, 1.0, -1.5);
424 params.camera_position.rotateXZBy(45);
425 params.camera_lookat.set(0, 0, 0);
426 // Set orthogonal projection
427 params.camera_projection_matrix.buildProjectionMatrixOrthoLH(
429 params.ambient_light.set(1.0, 0.2, 0.2, 0.2);
430 params.light_position.set(10, 100, -50);
431 params.light_color.set(1.0, 0.5, 0.5, 0.5);
432 params.light_radius = 1000;
434 cc->inventory_texture =
435 tsrc->generateTextureFromMesh(params);
437 // render-to-target didn't work
438 if(cc->inventory_texture == NULL)
440 cc->inventory_texture =
441 tsrc->getTexture(f.tiledef[0].name);
446 Use the node mesh as the wield mesh
449 // Scale to proper wield mesh proportions
450 scaleMesh(node_mesh, v3f(30.0, 30.0, 30.0)
453 cc->wield_mesh = node_mesh;
454 cc->wield_mesh->grab();
456 //no way reference count can be smaller than 2 in this place!
457 assert(cc->wield_mesh->getReferenceCount() >= 2);
461 m_clientcached.set(name, cc);
465 ClientCached* getClientCached(const std::string &name,
466 IGameDef *gamedef) const
468 ClientCached *cc = NULL;
469 m_clientcached.get(name, &cc);
473 if(get_current_thread_id() == m_main_thread)
475 return createClientCachedDirect(name, gamedef);
479 // We're gonna ask the result to be put into here
480 ResultQueue<std::string, ClientCached*, u8, u8> result_queue;
481 // Throw a request in
482 m_get_clientcached_queue.add(name, 0, 0, &result_queue);
484 // Wait result for a second
485 GetResult<std::string, ClientCached*, u8, u8>
486 result = result_queue.pop_front(1000);
487 // Check that at least something worked OK
488 assert(result.key == name);
492 catch(ItemNotFoundException &e)
494 errorstream<<"Waiting for clientcached timed out."<<std::endl;
495 return &m_dummy_clientcached;
499 // Get item inventory texture
500 virtual video::ITexture* getInventoryTexture(const std::string &name,
501 IGameDef *gamedef) const
503 ClientCached *cc = getClientCached(name, gamedef);
506 return cc->inventory_texture;
508 // Get item wield mesh
509 virtual scene::IMesh* getWieldMesh(const std::string &name,
510 IGameDef *gamedef) const
512 ClientCached *cc = getClientCached(name, gamedef);
515 return cc->wield_mesh;
520 for(std::map<std::string, ItemDefinition*>::const_iterator
521 i = m_item_definitions.begin();
522 i != m_item_definitions.end(); i++)
526 m_item_definitions.clear();
529 // Add the four builtin items:
531 // "unknown" is returned whenever an undefined item
532 // is accessed (is also the unknown node)
533 // "air" is the air node
534 // "ignore" is the ignore node
536 ItemDefinition* hand_def = new ItemDefinition;
538 hand_def->wield_image = "wieldhand.png";
539 hand_def->tool_capabilities = new ToolCapabilities;
540 m_item_definitions.insert(std::make_pair("", hand_def));
542 ItemDefinition* unknown_def = new ItemDefinition;
543 unknown_def->type = ITEM_NODE;
544 unknown_def->name = "unknown";
545 m_item_definitions.insert(std::make_pair("unknown", unknown_def));
547 ItemDefinition* air_def = new ItemDefinition;
548 air_def->type = ITEM_NODE;
549 air_def->name = "air";
550 m_item_definitions.insert(std::make_pair("air", air_def));
552 ItemDefinition* ignore_def = new ItemDefinition;
553 ignore_def->type = ITEM_NODE;
554 ignore_def->name = "ignore";
555 m_item_definitions.insert(std::make_pair("ignore", ignore_def));
557 virtual void registerItem(const ItemDefinition &def)
559 verbosestream<<"ItemDefManager: registering \""<<def.name<<"\""<<std::endl;
560 // Ensure that the "" item (the hand) always has ToolCapabilities
562 assert(def.tool_capabilities != NULL);
564 if(m_item_definitions.count(def.name) == 0)
565 m_item_definitions[def.name] = new ItemDefinition(def);
567 *(m_item_definitions[def.name]) = def;
569 // Remove conflicting alias if it exists
570 bool alias_removed = (m_aliases.erase(def.name) != 0);
572 infostream<<"ItemDefManager: erased alias "<<def.name
573 <<" because item was defined"<<std::endl;
575 virtual void registerAlias(const std::string &name,
576 const std::string &convert_to)
578 if(m_item_definitions.find(name) == m_item_definitions.end())
580 verbosestream<<"ItemDefManager: setting alias "<<name
581 <<" -> "<<convert_to<<std::endl;
582 m_aliases[name] = convert_to;
585 void serialize(std::ostream &os, u16 protocol_version)
587 writeU8(os, 0); // version
588 u16 count = m_item_definitions.size();
590 for(std::map<std::string, ItemDefinition*>::const_iterator
591 i = m_item_definitions.begin();
592 i != m_item_definitions.end(); i++)
594 ItemDefinition *def = i->second;
595 // Serialize ItemDefinition and write wrapped in a string
596 std::ostringstream tmp_os(std::ios::binary);
597 def->serialize(tmp_os, protocol_version);
598 os<<serializeString(tmp_os.str());
600 writeU16(os, m_aliases.size());
601 for(std::map<std::string, std::string>::const_iterator
602 i = m_aliases.begin(); i != m_aliases.end(); i++)
604 os<<serializeString(i->first);
605 os<<serializeString(i->second);
608 void deSerialize(std::istream &is)
613 int version = readU8(is);
615 throw SerializationError("unsupported ItemDefManager version");
616 u16 count = readU16(is);
617 for(u16 i=0; i<count; i++)
619 // Deserialize a string and grab an ItemDefinition from it
620 std::istringstream tmp_is(deSerializeString(is), std::ios::binary);
622 def.deSerialize(tmp_is);
626 u16 num_aliases = readU16(is);
627 for(u16 i=0; i<num_aliases; i++)
629 std::string name = deSerializeString(is);
630 std::string convert_to = deSerializeString(is);
631 registerAlias(name, convert_to);
634 void processQueue(IGameDef *gamedef)
637 while(!m_get_clientcached_queue.empty())
639 GetRequest<std::string, ClientCached*, u8, u8>
640 request = m_get_clientcached_queue.pop();
642 m_get_clientcached_queue.pushResult(request,
643 createClientCachedDirect(request.key, gamedef));
649 std::map<std::string, ItemDefinition*> m_item_definitions;
651 std::map<std::string, std::string> m_aliases;
653 // The id of the thread that is allowed to use irrlicht directly
654 threadid_t m_main_thread;
655 // A reference to this can be returned when nothing is found, to avoid NULLs
656 mutable ClientCached m_dummy_clientcached;
657 // Cached textures and meshes
658 mutable MutexedMap<std::string, ClientCached*> m_clientcached;
659 // Queued clientcached fetches (to be processed by the main thread)
660 mutable RequestQueue<std::string, ClientCached*, u8, u8> m_get_clientcached_queue;
664 IWritableItemDefManager* createItemDefManager()
666 return new CItemDefManager();