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"
30 #include "wieldmesh.h"
34 #include "main.h" // g_settings
36 #include "util/serialize.h"
37 #include "util/container.h"
38 #include "util/thread.h"
49 ItemDefinition::ItemDefinition()
54 ItemDefinition::ItemDefinition(const ItemDefinition &def)
60 ItemDefinition& ItemDefinition::operator=(const ItemDefinition &def)
69 description = def.description;
70 inventory_image = def.inventory_image;
71 wield_image = def.wield_image;
72 wield_scale = def.wield_scale;
73 stack_max = def.stack_max;
75 liquids_pointable = def.liquids_pointable;
76 if(def.tool_capabilities)
78 tool_capabilities = new ToolCapabilities(
79 *def.tool_capabilities);
82 node_placement_prediction = def.node_placement_prediction;
83 sound_place = def.sound_place;
88 ItemDefinition::~ItemDefinition()
93 void ItemDefinition::resetInitial()
95 // Initialize pointers to NULL so reset() does not delete undefined pointers
96 tool_capabilities = NULL;
100 void ItemDefinition::reset()
105 inventory_image = "";
107 wield_scale = v3f(1.0, 1.0, 1.0);
110 liquids_pointable = false;
111 if(tool_capabilities)
113 delete tool_capabilities;
114 tool_capabilities = NULL;
117 sound_place = SimpleSoundSpec();
120 node_placement_prediction = "";
123 void ItemDefinition::serialize(std::ostream &os, u16 protocol_version) const
125 if(protocol_version <= 17)
126 writeU8(os, 1); // version
127 else if(protocol_version <= 20)
128 writeU8(os, 2); // version
130 writeU8(os, 3); // version
132 os<<serializeString(name);
133 os<<serializeString(description);
134 os<<serializeString(inventory_image);
135 os<<serializeString(wield_image);
136 writeV3F1000(os, wield_scale);
137 writeS16(os, stack_max);
139 writeU8(os, liquids_pointable);
140 std::string tool_capabilities_s = "";
141 if(tool_capabilities){
142 std::ostringstream tmp_os(std::ios::binary);
143 tool_capabilities->serialize(tmp_os, protocol_version);
144 tool_capabilities_s = tmp_os.str();
146 os<<serializeString(tool_capabilities_s);
147 writeU16(os, groups.size());
148 for(std::map<std::string, int>::const_iterator
149 i = groups.begin(); i != groups.end(); i++){
150 os<<serializeString(i->first);
151 writeS16(os, i->second);
153 os<<serializeString(node_placement_prediction);
154 if(protocol_version > 17){
155 //serializeSimpleSoundSpec(sound_place, os);
156 os<<serializeString(sound_place.name);
157 writeF1000(os, sound_place.gain);
159 if(protocol_version > 20){
160 writeF1000(os, range);
164 void ItemDefinition::deSerialize(std::istream &is)
170 int version = readU8(is);
171 if(version < 1 || version > 3)
172 throw SerializationError("unsupported ItemDefinition version");
173 type = (enum ItemType)readU8(is);
174 name = deSerializeString(is);
175 description = deSerializeString(is);
176 inventory_image = deSerializeString(is);
177 wield_image = deSerializeString(is);
178 wield_scale = readV3F1000(is);
179 stack_max = readS16(is);
181 liquids_pointable = readU8(is);
182 std::string tool_capabilities_s = deSerializeString(is);
183 if(!tool_capabilities_s.empty())
185 std::istringstream tmp_is(tool_capabilities_s, std::ios::binary);
186 tool_capabilities = new ToolCapabilities;
187 tool_capabilities->deSerialize(tmp_is);
190 u32 groups_size = readU16(is);
191 for(u32 i=0; i<groups_size; i++){
192 std::string name = deSerializeString(is);
193 int value = readS16(is);
194 groups[name] = value;
197 // We cant be sure that node_placement_prediction is send in version 1
199 node_placement_prediction = deSerializeString(is);
200 }catch(SerializationError &e) {};
201 // Set the old default sound
202 sound_place.name = "default_place_node";
203 sound_place.gain = 0.5;
204 } else if(version >= 2) {
205 node_placement_prediction = deSerializeString(is);
206 //deserializeSimpleSoundSpec(sound_place, is);
207 sound_place.name = deSerializeString(is);
208 sound_place.gain = readF1000(is);
211 range = readF1000(is);
213 // If you add anything here, insert it primarily inside the try-catch
214 // block to not need to increase the version.
216 }catch(SerializationError &e) {};
223 // SUGG: Support chains of aliases?
225 class CItemDefManager: public IWritableItemDefManager
230 video::ITexture *inventory_texture;
231 scene::IMesh *wield_mesh;
234 inventory_texture(NULL),
245 m_main_thread = get_current_thread_id();
249 virtual ~CItemDefManager()
252 const std::list<ClientCached*> &values = m_clientcached.getValues();
253 for(std::list<ClientCached*>::const_iterator
254 i = values.begin(); i != values.end(); ++i)
256 ClientCached *cc = *i;
258 cc->wield_mesh->drop();
263 for (std::map<std::string, ItemDefinition*>::iterator iter =
264 m_item_definitions.begin(); iter != m_item_definitions.end();
268 m_item_definitions.clear();
270 virtual const ItemDefinition& get(const std::string &name_) const
272 // Convert name according to possible alias
273 std::string name = getAlias(name_);
274 // Get the definition
275 std::map<std::string, ItemDefinition*>::const_iterator i;
276 i = m_item_definitions.find(name);
277 if(i == m_item_definitions.end())
278 i = m_item_definitions.find("unknown");
279 assert(i != m_item_definitions.end());
282 virtual std::string getAlias(const std::string &name) const
284 std::map<std::string, std::string>::const_iterator i;
285 i = m_aliases.find(name);
286 if(i != m_aliases.end())
290 virtual std::set<std::string> getAll() const
292 std::set<std::string> result;
293 for(std::map<std::string, ItemDefinition*>::const_iterator
294 i = m_item_definitions.begin();
295 i != m_item_definitions.end(); i++)
297 result.insert(i->first);
299 for(std::map<std::string, std::string>::const_iterator
300 i = m_aliases.begin();
301 i != m_aliases.end(); i++)
303 result.insert(i->first);
307 virtual bool isKnown(const std::string &name_) const
309 // Convert name according to possible alias
310 std::string name = getAlias(name_);
311 // Get the definition
312 std::map<std::string, ItemDefinition*>::const_iterator i;
313 return m_item_definitions.find(name) != m_item_definitions.end();
317 ClientCached* createClientCachedDirect(const std::string &name,
318 IGameDef *gamedef) const
320 infostream<<"Lazily creating item texture and mesh for \""
321 <<name<<"\""<<std::endl;
323 // This is not thread-safe
324 assert(get_current_thread_id() == m_main_thread);
326 // Skip if already in cache
327 ClientCached *cc = NULL;
328 m_clientcached.get(name, &cc);
332 ITextureSource *tsrc = gamedef->getTextureSource();
333 INodeDefManager *nodedef = gamedef->getNodeDefManager();
334 const ItemDefinition &def = get(name);
336 // Create new ClientCached
337 cc = new ClientCached();
339 // Create an inventory texture
340 cc->inventory_texture = NULL;
341 if(def.inventory_image != "")
342 cc->inventory_texture = tsrc->getTexture(def.inventory_image);
344 // Additional processing for nodes:
345 // - Create a wield mesh if WieldMeshSceneNode can't render
346 // the node on its own.
347 // - If inventory_texture isn't set yet, create one using
348 // render-to-texture.
349 if (def.type == ITEM_NODE) {
350 // Get node properties
351 content_t id = nodedef->getId(name);
352 const ContentFeatures &f = nodedef->get(id);
354 bool need_rtt_mesh = cc->inventory_texture == NULL;
356 // Keep this in sync with WieldMeshSceneNode::setItem()
357 bool need_wield_mesh =
359 f.drawtype == NDT_NORMAL ||
360 f.drawtype == NDT_ALLFACES ||
361 f.drawtype == NDT_AIRLIKE);
363 scene::IMesh *node_mesh = NULL;
365 bool reenable_shaders = false;
367 if (need_rtt_mesh || need_wield_mesh) {
369 if (f.param_type == CPT_LIGHT)
373 Make a mesh from the node
375 if (g_settings->getBool("enable_shaders")) {
376 reenable_shaders = true;
377 g_settings->setBool("enable_shaders", false);
379 MeshMakeData mesh_make_data(gamedef);
381 if (f.param_type_2 == CPT2_WALLMOUNTED)
383 MapNode mesh_make_node(id, param1, param2);
384 mesh_make_data.fillSingleNode(&mesh_make_node);
385 MapBlockMesh mapblock_mesh(&mesh_make_data, v3s16(0, 0, 0));
386 node_mesh = mapblock_mesh.getMesh();
388 video::SColor c(255, 255, 255, 255);
389 setMeshColor(node_mesh, c);
391 // scale and translate the mesh so it's a
392 // unit cube centered on the origin
393 scaleMesh(node_mesh, v3f(1.0/BS, 1.0/BS, 1.0/BS));
394 translateMesh(node_mesh, v3f(-1.0, -1.0, -1.0));
398 Draw node mesh into a render target texture
401 TextureFromMeshParams params;
402 params.mesh = node_mesh;
403 params.dim.set(64, 64);
404 params.rtt_texture_name = "INVENTORY_"
406 params.delete_texture_on_shutdown = true;
407 params.camera_position.set(0, 1.0, -1.5);
408 params.camera_position.rotateXZBy(45);
409 params.camera_lookat.set(0, 0, 0);
410 // Set orthogonal projection
411 params.camera_projection_matrix.buildProjectionMatrixOrthoLH(
413 params.ambient_light.set(1.0, 0.2, 0.2, 0.2);
414 params.light_position.set(10, 100, -50);
415 params.light_color.set(1.0, 0.5, 0.5, 0.5);
416 params.light_radius = 1000;
419 params.camera_position.set(0, -1.0, -1.5);
420 params.camera_position.rotateXZBy(45);
421 params.light_position.set(10, -100, -50);
423 cc->inventory_texture =
424 tsrc->generateTextureFromMesh(params);
426 // render-to-target didn't work
427 if (cc->inventory_texture == NULL) {
428 cc->inventory_texture =
429 tsrc->getTexture(f.tiledef[0].name);
434 Use the node mesh as the wield mesh
436 if (need_wield_mesh) {
437 cc->wield_mesh = node_mesh;
438 cc->wield_mesh->grab();
440 // no way reference count can be smaller than 2 in this place!
441 assert(cc->wield_mesh->getReferenceCount() >= 2);
447 if (reenable_shaders)
448 g_settings->setBool("enable_shaders",true);
452 m_clientcached.set(name, cc);
456 ClientCached* getClientCached(const std::string &name,
457 IGameDef *gamedef) const
459 ClientCached *cc = NULL;
460 m_clientcached.get(name, &cc);
464 if(get_current_thread_id() == m_main_thread)
466 return createClientCachedDirect(name, gamedef);
470 // We're gonna ask the result to be put into here
471 static ResultQueue<std::string, ClientCached*, u8, u8> result_queue;
473 // Throw a request in
474 m_get_clientcached_queue.add(name, 0, 0, &result_queue);
477 // Wait result for a second
478 GetResult<std::string, ClientCached*, u8, u8>
479 result = result_queue.pop_front(1000);
481 if (result.key == name) {
486 catch(ItemNotFoundException &e)
488 errorstream<<"Waiting for clientcached " << name << " timed out."<<std::endl;
489 return &m_dummy_clientcached;
493 // Get item inventory texture
494 virtual video::ITexture* getInventoryTexture(const std::string &name,
495 IGameDef *gamedef) const
497 ClientCached *cc = getClientCached(name, gamedef);
500 return cc->inventory_texture;
502 // Get item wield mesh
503 virtual scene::IMesh* getWieldMesh(const std::string &name,
504 IGameDef *gamedef) const
506 ClientCached *cc = getClientCached(name, gamedef);
509 return cc->wield_mesh;
514 for(std::map<std::string, ItemDefinition*>::const_iterator
515 i = m_item_definitions.begin();
516 i != m_item_definitions.end(); i++)
520 m_item_definitions.clear();
523 // Add the four builtin items:
525 // "unknown" is returned whenever an undefined item
526 // is accessed (is also the unknown node)
527 // "air" is the air node
528 // "ignore" is the ignore node
530 ItemDefinition* hand_def = new ItemDefinition;
532 hand_def->wield_image = "wieldhand.png";
533 hand_def->tool_capabilities = new ToolCapabilities;
534 m_item_definitions.insert(std::make_pair("", hand_def));
536 ItemDefinition* unknown_def = new ItemDefinition;
537 unknown_def->type = ITEM_NODE;
538 unknown_def->name = "unknown";
539 m_item_definitions.insert(std::make_pair("unknown", unknown_def));
541 ItemDefinition* air_def = new ItemDefinition;
542 air_def->type = ITEM_NODE;
543 air_def->name = "air";
544 m_item_definitions.insert(std::make_pair("air", air_def));
546 ItemDefinition* ignore_def = new ItemDefinition;
547 ignore_def->type = ITEM_NODE;
548 ignore_def->name = "ignore";
549 m_item_definitions.insert(std::make_pair("ignore", ignore_def));
551 virtual void registerItem(const ItemDefinition &def)
553 verbosestream<<"ItemDefManager: registering \""<<def.name<<"\""<<std::endl;
554 // Ensure that the "" item (the hand) always has ToolCapabilities
556 assert(def.tool_capabilities != NULL);
558 if(m_item_definitions.count(def.name) == 0)
559 m_item_definitions[def.name] = new ItemDefinition(def);
561 *(m_item_definitions[def.name]) = def;
563 // Remove conflicting alias if it exists
564 bool alias_removed = (m_aliases.erase(def.name) != 0);
566 infostream<<"ItemDefManager: erased alias "<<def.name
567 <<" because item was defined"<<std::endl;
569 virtual void registerAlias(const std::string &name,
570 const std::string &convert_to)
572 if(m_item_definitions.find(name) == m_item_definitions.end())
574 verbosestream<<"ItemDefManager: setting alias "<<name
575 <<" -> "<<convert_to<<std::endl;
576 m_aliases[name] = convert_to;
579 void serialize(std::ostream &os, u16 protocol_version)
581 writeU8(os, 0); // version
582 u16 count = m_item_definitions.size();
584 for(std::map<std::string, ItemDefinition*>::const_iterator
585 i = m_item_definitions.begin();
586 i != m_item_definitions.end(); i++)
588 ItemDefinition *def = i->second;
589 // Serialize ItemDefinition and write wrapped in a string
590 std::ostringstream tmp_os(std::ios::binary);
591 def->serialize(tmp_os, protocol_version);
592 os<<serializeString(tmp_os.str());
594 writeU16(os, m_aliases.size());
595 for(std::map<std::string, std::string>::const_iterator
596 i = m_aliases.begin(); i != m_aliases.end(); i++)
598 os<<serializeString(i->first);
599 os<<serializeString(i->second);
602 void deSerialize(std::istream &is)
607 int version = readU8(is);
609 throw SerializationError("unsupported ItemDefManager version");
610 u16 count = readU16(is);
611 for(u16 i=0; i<count; i++)
613 // Deserialize a string and grab an ItemDefinition from it
614 std::istringstream tmp_is(deSerializeString(is), std::ios::binary);
616 def.deSerialize(tmp_is);
620 u16 num_aliases = readU16(is);
621 for(u16 i=0; i<num_aliases; i++)
623 std::string name = deSerializeString(is);
624 std::string convert_to = deSerializeString(is);
625 registerAlias(name, convert_to);
628 void processQueue(IGameDef *gamedef)
631 //NOTE this is only thread safe for ONE consumer thread!
632 while(!m_get_clientcached_queue.empty())
634 GetRequest<std::string, ClientCached*, u8, u8>
635 request = m_get_clientcached_queue.pop();
637 m_get_clientcached_queue.pushResult(request,
638 createClientCachedDirect(request.key, gamedef));
644 std::map<std::string, ItemDefinition*> m_item_definitions;
646 std::map<std::string, std::string> m_aliases;
648 // The id of the thread that is allowed to use irrlicht directly
649 threadid_t m_main_thread;
650 // A reference to this can be returned when nothing is found, to avoid NULLs
651 mutable ClientCached m_dummy_clientcached;
652 // Cached textures and meshes
653 mutable MutexedMap<std::string, ClientCached*> m_clientcached;
654 // Queued clientcached fetches (to be processed by the main thread)
655 mutable RequestQueue<std::string, ClientCached*, u8, u8> m_get_clientcached_queue;
659 IWritableItemDefManager* createItemDefManager()
661 return new CItemDefManager();