Add Entity get_texture_mod() to Lua API
[oweals/minetest.git] / src / content_cao.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-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 <ICameraSceneNode.h>
21 #include <ITextSceneNode.h>
22 #include <IBillboardSceneNode.h>
23 #include <IMeshManipulator.h>
24 #include <IAnimatedMeshSceneNode.h>
25 #include <IBoneSceneNode.h>
26 #include "content_cao.h"
27 #include "util/numeric.h" // For IntervalLimiter
28 #include "util/serialize.h"
29 #include "util/basic_macros.h"
30 #include "client/tile.h"
31 #include "environment.h"
32 #include "collision.h"
33 #include "settings.h"
34 #include "serialization.h" // For decompressZlib
35 #include "clientobject.h"
36 #include "mesh.h"
37 #include "itemdef.h"
38 #include "tool.h"
39 #include "content_cso.h"
40 #include "sound.h"
41 #include "nodedef.h"
42 #include "localplayer.h"
43 #include "map.h"
44 #include "camera.h" // CameraModes
45 #include "wieldmesh.h"
46 #include "log.h"
47
48 class Settings;
49 struct ToolCapabilities;
50
51 UNORDERED_MAP<u16, ClientActiveObject::Factory> ClientActiveObject::m_types;
52
53 SmoothTranslator::SmoothTranslator():
54         vect_old(0,0,0),
55         vect_show(0,0,0),
56         vect_aim(0,0,0),
57         anim_counter(0),
58         anim_time(0),
59         anim_time_counter(0),
60         aim_is_end(true)
61 {}
62
63 void SmoothTranslator::init(v3f vect)
64 {
65         vect_old = vect;
66         vect_show = vect;
67         vect_aim = vect;
68         anim_counter = 0;
69         anim_time = 0;
70         anim_time_counter = 0;
71         aim_is_end = true;
72 }
73
74 void SmoothTranslator::sharpen()
75 {
76         init(vect_show);
77 }
78
79 void SmoothTranslator::update(v3f vect_new, bool is_end_position, float update_interval)
80 {
81         aim_is_end = is_end_position;
82         vect_old = vect_show;
83         vect_aim = vect_new;
84         if(update_interval > 0)
85         {
86                 anim_time = update_interval;
87         } else {
88                 if(anim_time < 0.001 || anim_time > 1.0)
89                         anim_time = anim_time_counter;
90                 else
91                         anim_time = anim_time * 0.9 + anim_time_counter * 0.1;
92         }
93         anim_time_counter = 0;
94         anim_counter = 0;
95 }
96
97 void SmoothTranslator::translate(f32 dtime)
98 {
99         anim_time_counter = anim_time_counter + dtime;
100         anim_counter = anim_counter + dtime;
101         v3f vect_move = vect_aim - vect_old;
102         f32 moveratio = 1.0;
103         if(anim_time > 0.001)
104                 moveratio = anim_time_counter / anim_time;
105         // Move a bit less than should, to avoid oscillation
106         moveratio = moveratio * 0.8;
107         float move_end = 1.5;
108         if(aim_is_end)
109                 move_end = 1.0;
110         if(moveratio > move_end)
111                 moveratio = move_end;
112         vect_show = vect_old + vect_move * moveratio;
113 }
114
115 bool SmoothTranslator::is_moving()
116 {
117         return ((anim_time_counter / anim_time) < 1.4);
118 }
119
120 /*
121         Other stuff
122 */
123
124 static void setBillboardTextureMatrix(scene::IBillboardSceneNode *bill,
125                 float txs, float tys, int col, int row)
126 {
127         video::SMaterial& material = bill->getMaterial(0);
128         core::matrix4& matrix = material.getTextureMatrix(0);
129         matrix.setTextureTranslate(txs*col, tys*row);
130         matrix.setTextureScale(txs, tys);
131 }
132
133 /*
134         TestCAO
135 */
136
137 class TestCAO : public ClientActiveObject
138 {
139 public:
140         TestCAO(Client *client, ClientEnvironment *env);
141         virtual ~TestCAO();
142
143         ActiveObjectType getType() const
144         {
145                 return ACTIVEOBJECT_TYPE_TEST;
146         }
147
148         static ClientActiveObject* create(Client *client, ClientEnvironment *env);
149
150         void addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc,
151                         IrrlichtDevice *irr);
152         void removeFromScene(bool permanent);
153         void updateLight(u8 light_at_pos);
154         v3s16 getLightPosition();
155         void updateNodePos();
156
157         void step(float dtime, ClientEnvironment *env);
158
159         void processMessage(const std::string &data);
160
161         bool getCollisionBox(aabb3f *toset) const { return false; }
162 private:
163         scene::IMeshSceneNode *m_node;
164         v3f m_position;
165 };
166
167 // Prototype
168 TestCAO proto_TestCAO(NULL, NULL);
169
170 TestCAO::TestCAO(Client *client, ClientEnvironment *env):
171         ClientActiveObject(0, client, env),
172         m_node(NULL),
173         m_position(v3f(0,10*BS,0))
174 {
175         ClientActiveObject::registerType(getType(), create);
176 }
177
178 TestCAO::~TestCAO()
179 {
180 }
181
182 ClientActiveObject* TestCAO::create(Client *client, ClientEnvironment *env)
183 {
184         return new TestCAO(client, env);
185 }
186
187 void TestCAO::addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc,
188                         IrrlichtDevice *irr)
189 {
190         if(m_node != NULL)
191                 return;
192
193         //video::IVideoDriver* driver = smgr->getVideoDriver();
194
195         scene::SMesh *mesh = new scene::SMesh();
196         scene::IMeshBuffer *buf = new scene::SMeshBuffer();
197         video::SColor c(255,255,255,255);
198         video::S3DVertex vertices[4] =
199         {
200                 video::S3DVertex(-BS/2,-BS/4,0, 0,0,0, c, 0,1),
201                 video::S3DVertex(BS/2,-BS/4,0, 0,0,0, c, 1,1),
202                 video::S3DVertex(BS/2,BS/4,0, 0,0,0, c, 1,0),
203                 video::S3DVertex(-BS/2,BS/4,0, 0,0,0, c, 0,0),
204         };
205         u16 indices[] = {0,1,2,2,3,0};
206         buf->append(vertices, 4, indices, 6);
207         // Set material
208         buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
209         buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
210         buf->getMaterial().setTexture(0, tsrc->getTextureForMesh("rat.png"));
211         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
212         buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
213         buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
214         // Add to mesh
215         mesh->addMeshBuffer(buf);
216         buf->drop();
217         m_node = smgr->addMeshSceneNode(mesh, NULL);
218         mesh->drop();
219         updateNodePos();
220 }
221
222 void TestCAO::removeFromScene(bool permanent)
223 {
224         if(m_node == NULL)
225                 return;
226
227         m_node->remove();
228         m_node = NULL;
229 }
230
231 void TestCAO::updateLight(u8 light_at_pos)
232 {
233 }
234
235 v3s16 TestCAO::getLightPosition()
236 {
237         return floatToInt(m_position, BS);
238 }
239
240 void TestCAO::updateNodePos()
241 {
242         if(m_node == NULL)
243                 return;
244
245         m_node->setPosition(m_position);
246         //m_node->setRotation(v3f(0, 45, 0));
247 }
248
249 void TestCAO::step(float dtime, ClientEnvironment *env)
250 {
251         if(m_node)
252         {
253                 v3f rot = m_node->getRotation();
254                 //infostream<<"dtime="<<dtime<<", rot.Y="<<rot.Y<<std::endl;
255                 rot.Y += dtime * 180;
256                 m_node->setRotation(rot);
257         }
258 }
259
260 void TestCAO::processMessage(const std::string &data)
261 {
262         infostream<<"TestCAO: Got data: "<<data<<std::endl;
263         std::istringstream is(data, std::ios::binary);
264         u16 cmd;
265         is>>cmd;
266         if(cmd == 0)
267         {
268                 v3f newpos;
269                 is>>newpos.X;
270                 is>>newpos.Y;
271                 is>>newpos.Z;
272                 m_position = newpos;
273                 updateNodePos();
274         }
275 }
276
277 /*
278         ItemCAO
279 */
280
281 class ItemCAO : public ClientActiveObject
282 {
283 public:
284         ItemCAO(Client *client, ClientEnvironment *env);
285         virtual ~ItemCAO();
286
287         ActiveObjectType getType() const
288         {
289                 return ACTIVEOBJECT_TYPE_ITEM;
290         }
291
292         static ClientActiveObject* create(Client *client, ClientEnvironment *env);
293
294         void addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc,
295                         IrrlichtDevice *irr);
296         void removeFromScene(bool permanent);
297         void updateLight(u8 light_at_pos);
298         v3s16 getLightPosition();
299         void updateNodePos();
300         void updateInfoText();
301         void updateTexture();
302
303         void step(float dtime, ClientEnvironment *env);
304
305         void processMessage(const std::string &data);
306
307         void initialize(const std::string &data);
308
309         aabb3f *getSelectionBox()
310                 {return &m_selection_box;}
311         v3f getPosition()
312                 {return m_position;}
313         inline float getYaw() const
314                 {return 0;}
315         std::string infoText()
316                 {return m_infotext;}
317
318         bool getCollisionBox(aabb3f *toset) const { return false; }
319 private:
320         aabb3f m_selection_box;
321         scene::IMeshSceneNode *m_node;
322         v3f m_position;
323         std::string m_itemstring;
324         std::string m_infotext;
325 };
326
327 #include "inventory.h"
328
329 // Prototype
330 ItemCAO proto_ItemCAO(NULL, NULL);
331
332 ItemCAO::ItemCAO(Client *client, ClientEnvironment *env):
333         ClientActiveObject(0, client, env),
334         m_selection_box(-BS/3.,0.0,-BS/3., BS/3.,BS*2./3.,BS/3.),
335         m_node(NULL),
336         m_position(v3f(0,10*BS,0))
337 {
338         if(!client && !env)
339         {
340                 ClientActiveObject::registerType(getType(), create);
341         }
342 }
343
344 ItemCAO::~ItemCAO()
345 {
346 }
347
348 ClientActiveObject* ItemCAO::create(Client *client, ClientEnvironment *env)
349 {
350         return new ItemCAO(client, env);
351 }
352
353 void ItemCAO::addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc,
354                         IrrlichtDevice *irr)
355 {
356         if(m_node != NULL)
357                 return;
358
359         //video::IVideoDriver* driver = smgr->getVideoDriver();
360
361         scene::SMesh *mesh = new scene::SMesh();
362         scene::IMeshBuffer *buf = new scene::SMeshBuffer();
363         video::SColor c(255,255,255,255);
364         video::S3DVertex vertices[4] =
365         {
366                 /*video::S3DVertex(-BS/2,-BS/4,0, 0,0,0, c, 0,1),
367                 video::S3DVertex(BS/2,-BS/4,0, 0,0,0, c, 1,1),
368                 video::S3DVertex(BS/2,BS/4,0, 0,0,0, c, 1,0),
369                 video::S3DVertex(-BS/2,BS/4,0, 0,0,0, c, 0,0),*/
370                 video::S3DVertex(BS/3.,0,0, 0,0,0, c, 0,1),
371                 video::S3DVertex(-BS/3.,0,0, 0,0,0, c, 1,1),
372                 video::S3DVertex(-BS/3.,0+BS*2./3.,0, 0,0,0, c, 1,0),
373                 video::S3DVertex(BS/3.,0+BS*2./3.,0, 0,0,0, c, 0,0),
374         };
375         u16 indices[] = {0,1,2,2,3,0};
376         buf->append(vertices, 4, indices, 6);
377         // Set material
378         buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
379         buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
380         // Initialize with a generated placeholder texture
381         buf->getMaterial().setTexture(0, tsrc->getTexture(""));
382         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
383         buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
384         buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
385         // Add to mesh
386         mesh->addMeshBuffer(buf);
387         buf->drop();
388         m_node = smgr->addMeshSceneNode(mesh, NULL);
389         mesh->drop();
390         updateNodePos();
391
392         /*
393                 Update image of node
394         */
395
396         updateTexture();
397 }
398
399 void ItemCAO::removeFromScene(bool permanent)
400 {
401         if(m_node == NULL)
402                 return;
403
404         m_node->remove();
405         m_node = NULL;
406 }
407
408 void ItemCAO::updateLight(u8 light_at_pos)
409 {
410         if(m_node == NULL)
411                 return;
412
413         u8 li = decode_light(light_at_pos);
414         video::SColor color(255,li,li,li);
415         setMeshColor(m_node->getMesh(), color);
416 }
417
418 v3s16 ItemCAO::getLightPosition()
419 {
420         return floatToInt(m_position + v3f(0,0.5*BS,0), BS);
421 }
422
423 void ItemCAO::updateNodePos()
424 {
425         if(m_node == NULL)
426                 return;
427
428         m_node->setPosition(m_position);
429 }
430
431 void ItemCAO::updateInfoText()
432 {
433         try{
434                 IItemDefManager *idef = m_client->idef();
435                 ItemStack item;
436                 item.deSerialize(m_itemstring, idef);
437                 if(item.isKnown(idef))
438                         m_infotext = item.getDefinition(idef).description;
439                 else
440                         m_infotext = "Unknown item: '" + m_itemstring + "'";
441                 if(item.count >= 2)
442                         m_infotext += " (" + itos(item.count) + ")";
443         }
444         catch(SerializationError &e)
445         {
446                 m_infotext = "Unknown item: '" + m_itemstring + "'";
447         }
448 }
449
450 void ItemCAO::updateTexture()
451 {
452         if(m_node == NULL)
453                 return;
454
455         // Create an inventory item to see what is its image
456         std::istringstream is(m_itemstring, std::ios_base::binary);
457         video::ITexture *texture = NULL;
458         try{
459                 IItemDefManager *idef = m_client->idef();
460                 ItemStack item;
461                 item.deSerialize(is, idef);
462                 texture = idef->getInventoryTexture(item.getDefinition(idef).name, m_client);
463         }
464         catch(SerializationError &e)
465         {
466                 warningstream<<FUNCTION_NAME
467                                 <<": error deSerializing itemstring \""
468                                 <<m_itemstring<<std::endl;
469         }
470
471         // Set meshbuffer texture
472         m_node->getMaterial(0).setTexture(0, texture);
473 }
474
475
476 void ItemCAO::step(float dtime, ClientEnvironment *env)
477 {
478         if(m_node)
479         {
480                 /*v3f rot = m_node->getRotation();
481                 rot.Y += dtime * 120;
482                 m_node->setRotation(rot);*/
483                 LocalPlayer *player = env->getLocalPlayer();
484                 assert(player);
485                 v3f rot = m_node->getRotation();
486                 rot.Y = 180.0 - (player->getYaw());
487                 m_node->setRotation(rot);
488         }
489 }
490
491 void ItemCAO::processMessage(const std::string &data)
492 {
493         //infostream<<"ItemCAO: Got message"<<std::endl;
494         std::istringstream is(data, std::ios::binary);
495         // command
496         u8 cmd = readU8(is);
497         if(cmd == 0)
498         {
499                 // pos
500                 m_position = readV3F1000(is);
501                 updateNodePos();
502         }
503         if(cmd == 1)
504         {
505                 // itemstring
506                 m_itemstring = deSerializeString(is);
507                 updateInfoText();
508                 updateTexture();
509         }
510 }
511
512 void ItemCAO::initialize(const std::string &data)
513 {
514         infostream<<"ItemCAO: Got init data"<<std::endl;
515
516         {
517                 std::istringstream is(data, std::ios::binary);
518                 // version
519                 u8 version = readU8(is);
520                 // check version
521                 if(version != 0)
522                         return;
523                 // pos
524                 m_position = readV3F1000(is);
525                 // itemstring
526                 m_itemstring = deSerializeString(is);
527         }
528
529         updateNodePos();
530         updateInfoText();
531 }
532
533 /*
534         GenericCAO
535 */
536
537 #include "genericobject.h"
538
539 GenericCAO::GenericCAO(Client *client, ClientEnvironment *env):
540                 ClientActiveObject(0, client, env),
541                 //
542                 m_is_player(false),
543                 m_is_local_player(false),
544                 //
545                 m_smgr(NULL),
546                 m_irr(NULL),
547                 m_client(NULL),
548                 m_selection_box(-BS/3.,-BS/3.,-BS/3., BS/3.,BS/3.,BS/3.),
549                 m_meshnode(NULL),
550                 m_animated_meshnode(NULL),
551                 m_wield_meshnode(NULL),
552                 m_spritenode(NULL),
553                 m_nametag(NULL),
554                 m_position(v3f(0,10*BS,0)),
555                 m_velocity(v3f(0,0,0)),
556                 m_acceleration(v3f(0,0,0)),
557                 m_yaw(0),
558                 m_hp(1),
559                 m_tx_size(1,1),
560                 m_tx_basepos(0,0),
561                 m_initial_tx_basepos_set(false),
562                 m_tx_select_horiz_by_yawpitch(false),
563                 m_animation_range(v2s32(0,0)),
564                 m_animation_speed(15),
565                 m_animation_blend(0),
566                 m_animation_loop(true),
567                 m_bone_position(UNORDERED_MAP<std::string, core::vector2d<v3f> >()),
568                 m_attachment_bone(""),
569                 m_attachment_position(v3f(0,0,0)),
570                 m_attachment_rotation(v3f(0,0,0)),
571                 m_attached_to_local(false),
572                 m_anim_frame(0),
573                 m_anim_num_frames(1),
574                 m_anim_framelength(0.2),
575                 m_anim_timer(0),
576                 m_reset_textures_timer(-1),
577                 m_previous_texture_modifier(""),
578                 m_current_texture_modifier(""),
579                 m_visuals_expired(false),
580                 m_step_distance_counter(0),
581                 m_last_light(255),
582                 m_is_visible(false)
583 {
584         if (client == NULL) {
585                 ClientActiveObject::registerType(getType(), create);
586         } else {
587                 m_client = client;
588         }
589 }
590
591 bool GenericCAO::getCollisionBox(aabb3f *toset) const
592 {
593         if (m_prop.physical)
594         {
595                 //update collision box
596                 toset->MinEdge = m_prop.collisionbox.MinEdge * BS;
597                 toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS;
598
599                 toset->MinEdge += m_position;
600                 toset->MaxEdge += m_position;
601
602                 return true;
603         }
604
605         return false;
606 }
607
608 bool GenericCAO::collideWithObjects() const
609 {
610         return m_prop.collideWithObjects;
611 }
612
613 void GenericCAO::initialize(const std::string &data)
614 {
615         infostream<<"GenericCAO: Got init data"<<std::endl;
616         processInitData(data);
617
618         if (m_is_player) {
619                 // Check if it's the current player
620                 LocalPlayer *player = m_env->getLocalPlayer();
621                 if (player && strcmp(player->getName(), m_name.c_str()) == 0) {
622                         m_is_local_player = true;
623                         m_is_visible = false;
624                         player->setCAO(this);
625                 }
626                 m_env->addPlayerName(m_name.c_str());
627         }
628 }
629
630 void GenericCAO::processInitData(const std::string &data)
631 {
632         std::istringstream is(data, std::ios::binary);
633         int num_messages = 0;
634         // version
635         u8 version = readU8(is);
636         // check version
637         if (version == 1) { // In PROTOCOL_VERSION 14
638                 m_name = deSerializeString(is);
639                 m_is_player = readU8(is);
640                 m_id = readS16(is);
641                 m_position = readV3F1000(is);
642                 m_yaw = readF1000(is);
643                 m_hp = readS16(is);
644                 num_messages = readU8(is);
645         } else if (version == 0) { // In PROTOCOL_VERSION 13
646                 m_name = deSerializeString(is);
647                 m_is_player = readU8(is);
648                 m_position = readV3F1000(is);
649                 m_yaw = readF1000(is);
650                 m_hp = readS16(is);
651                 num_messages = readU8(is);
652         } else {
653                 errorstream<<"GenericCAO: Unsupported init data version"
654                                 <<std::endl;
655                 return;
656         }
657
658         for (int i = 0; i < num_messages; i++) {
659                 std::string message = deSerializeLongString(is);
660                 processMessage(message);
661         }
662
663         pos_translator.init(m_position);
664         updateNodePos();
665 }
666
667 GenericCAO::~GenericCAO()
668 {
669         if (m_is_player) {
670                 m_env->removePlayerName(m_name.c_str());
671         }
672         removeFromScene(true);
673 }
674
675 aabb3f *GenericCAO::getSelectionBox()
676 {
677         if(!m_prop.is_visible || !m_is_visible || m_is_local_player || getParent() != NULL)
678                 return NULL;
679         return &m_selection_box;
680 }
681
682 v3f GenericCAO::getPosition()
683 {
684         if (getParent() != NULL) {
685                 scene::ISceneNode *node = getSceneNode();
686                 if (node)
687                         return node->getAbsolutePosition();
688                 else
689                         return m_position;
690         }
691         return pos_translator.vect_show;
692 }
693
694 scene::ISceneNode* GenericCAO::getSceneNode()
695 {
696         if (m_meshnode) {
697                 return m_meshnode;
698         } else if (m_animated_meshnode) {
699                 return m_animated_meshnode;
700         } else if (m_wield_meshnode) {
701                 return m_wield_meshnode;
702         } else if (m_spritenode) {
703                 return m_spritenode;
704         }
705         return NULL;
706 }
707
708 scene::IMeshSceneNode* GenericCAO::getMeshSceneNode()
709 {
710         return m_meshnode;
711 }
712
713 scene::IAnimatedMeshSceneNode* GenericCAO::getAnimatedMeshSceneNode()
714 {
715         return m_animated_meshnode;
716 }
717
718 WieldMeshSceneNode* GenericCAO::getWieldMeshSceneNode()
719 {
720         return m_wield_meshnode;
721 }
722
723 scene::IBillboardSceneNode* GenericCAO::getSpriteSceneNode()
724 {
725         return m_spritenode;
726 }
727
728 void GenericCAO::setChildrenVisible(bool toset)
729 {
730         for (std::vector<u16>::size_type i = 0; i < m_children.size(); i++) {
731                 GenericCAO *obj = m_env->getGenericCAO(m_children[i]);
732                 if (obj) {
733                         obj->setVisible(toset);
734                 }
735         }
736 }
737
738 void GenericCAO::setAttachments()
739 {
740         updateAttachments();
741 }
742
743 ClientActiveObject* GenericCAO::getParent()
744 {
745         ClientActiveObject *obj = NULL;
746
747         u16 attached_id = m_env->attachement_parent_ids[getId()];
748
749         if ((attached_id != 0) &&
750                         (attached_id != getId())) {
751                 obj = m_env->getActiveObject(attached_id);
752         }
753         return obj;
754 }
755
756 void GenericCAO::removeFromScene(bool permanent)
757 {
758         // Should be true when removing the object permanently and false when refreshing (eg: updating visuals)
759         if((m_env != NULL) && (permanent))
760         {
761                 for (std::vector<u16>::size_type i = 0; i < m_children.size(); i++) {
762                         u16 ci = m_children[i];
763                         if (m_env->attachement_parent_ids[ci] == getId()) {
764                                 m_env->attachement_parent_ids[ci] = 0;
765                         }
766                 }
767
768                 m_env->attachement_parent_ids[getId()] = 0;
769
770                 LocalPlayer* player = m_env->getLocalPlayer();
771                 if (this == player->parent) {
772                         player->parent = NULL;
773                         player->isAttached = false;
774                 }
775         }
776
777         if (m_meshnode) {
778                 m_meshnode->remove();
779                 m_meshnode->drop();
780                 m_meshnode = NULL;
781         } else if (m_animated_meshnode) {
782                 m_animated_meshnode->remove();
783                 m_animated_meshnode->drop();
784                 m_animated_meshnode = NULL;
785         } else if (m_wield_meshnode) {
786                 m_wield_meshnode->remove();
787                 m_wield_meshnode->drop();
788                 m_wield_meshnode = NULL;
789         } else if (m_spritenode) {
790                 m_spritenode->remove();
791                 m_spritenode->drop();
792                 m_spritenode = NULL;
793         }
794
795         if (m_nametag) {
796                 m_client->getCamera()->removeNametag(m_nametag);
797                 m_nametag = NULL;
798         }
799 }
800
801 void GenericCAO::addToScene(scene::ISceneManager *smgr,
802                 ITextureSource *tsrc, IrrlichtDevice *irr)
803 {
804         m_smgr = smgr;
805         m_irr = irr;
806
807         if (getSceneNode() != NULL) {
808                 return;
809         }
810
811         m_visuals_expired = false;
812
813         if (!m_prop.is_visible) {
814                 return;
815         }
816
817         if (m_prop.visual == "sprite") {
818                 infostream<<"GenericCAO::addToScene(): single_sprite"<<std::endl;
819                 m_spritenode = smgr->addBillboardSceneNode(
820                                 NULL, v2f(1, 1), v3f(0,0,0), -1);
821                 m_spritenode->grab();
822                 m_spritenode->setMaterialTexture(0,
823                                 tsrc->getTextureForMesh("unknown_node.png"));
824                 m_spritenode->setMaterialFlag(video::EMF_LIGHTING, false);
825                 m_spritenode->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
826                 m_spritenode->setMaterialType(video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF);
827                 m_spritenode->setMaterialFlag(video::EMF_FOG_ENABLE, true);
828                 u8 li = m_last_light;
829                 m_spritenode->setColor(video::SColor(255,li,li,li));
830                 m_spritenode->setSize(m_prop.visual_size*BS);
831                 {
832                         const float txs = 1.0 / 1;
833                         const float tys = 1.0 / 1;
834                         setBillboardTextureMatrix(m_spritenode,
835                                         txs, tys, 0, 0);
836                 }
837         } else if (m_prop.visual == "upright_sprite") {
838                 scene::SMesh *mesh = new scene::SMesh();
839                 double dx = BS * m_prop.visual_size.X / 2;
840                 double dy = BS * m_prop.visual_size.Y / 2;
841                 u8 li = m_last_light;
842                 video::SColor c(255, li, li, li);
843
844                 { // Front
845                         scene::IMeshBuffer *buf = new scene::SMeshBuffer();
846                         video::S3DVertex vertices[4] = {
847                                 video::S3DVertex(-dx, -dy, 0, 0,0,0, c, 1,1),
848                                 video::S3DVertex( dx, -dy, 0, 0,0,0, c, 0,1),
849                                 video::S3DVertex( dx,  dy, 0, 0,0,0, c, 0,0),
850                                 video::S3DVertex(-dx,  dy, 0, 0,0,0, c, 1,0),
851                         };
852                         u16 indices[] = {0,1,2,2,3,0};
853                         buf->append(vertices, 4, indices, 6);
854                         // Set material
855                         buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
856                         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
857                         buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
858                         buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
859                         // Add to mesh
860                         mesh->addMeshBuffer(buf);
861                         buf->drop();
862                 }
863                 { // Back
864                         scene::IMeshBuffer *buf = new scene::SMeshBuffer();
865                         video::S3DVertex vertices[4] = {
866                                 video::S3DVertex( dx,-dy, 0, 0,0,0, c, 1,1),
867                                 video::S3DVertex(-dx,-dy, 0, 0,0,0, c, 0,1),
868                                 video::S3DVertex(-dx, dy, 0, 0,0,0, c, 0,0),
869                                 video::S3DVertex( dx, dy, 0, 0,0,0, c, 1,0),
870                         };
871                         u16 indices[] = {0,1,2,2,3,0};
872                         buf->append(vertices, 4, indices, 6);
873                         // Set material
874                         buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
875                         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
876                         buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
877                         buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
878                         // Add to mesh
879                         mesh->addMeshBuffer(buf);
880                         buf->drop();
881                 }
882                 m_meshnode = smgr->addMeshSceneNode(mesh, NULL);
883                 m_meshnode->grab();
884                 mesh->drop();
885                 // Set it to use the materials of the meshbuffers directly.
886                 // This is needed for changing the texture in the future
887                 m_meshnode->setReadOnlyMaterials(true);
888         }
889         else if(m_prop.visual == "cube") {
890                 infostream<<"GenericCAO::addToScene(): cube"<<std::endl;
891                 scene::IMesh *mesh = createCubeMesh(v3f(BS,BS,BS));
892                 m_meshnode = smgr->addMeshSceneNode(mesh, NULL);
893                 m_meshnode->grab();
894                 mesh->drop();
895
896                 m_meshnode->setScale(v3f(m_prop.visual_size.X,
897                                 m_prop.visual_size.Y,
898                                 m_prop.visual_size.X));
899                 u8 li = m_last_light;
900                 setMeshColor(m_meshnode->getMesh(), video::SColor(255,li,li,li));
901
902                 m_meshnode->setMaterialFlag(video::EMF_LIGHTING, false);
903                 m_meshnode->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
904                 m_meshnode->setMaterialType(video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF);
905                 m_meshnode->setMaterialFlag(video::EMF_FOG_ENABLE, true);
906         }
907         else if(m_prop.visual == "mesh") {
908                 infostream<<"GenericCAO::addToScene(): mesh"<<std::endl;
909                 scene::IAnimatedMesh *mesh = m_client->getMesh(m_prop.mesh);
910                 if(mesh)
911                 {
912                         m_animated_meshnode = smgr->addAnimatedMeshSceneNode(mesh, NULL);
913                         m_animated_meshnode->grab();
914                         mesh->drop(); // The scene node took hold of it
915                         m_animated_meshnode->animateJoints(); // Needed for some animations
916                         m_animated_meshnode->setScale(v3f(m_prop.visual_size.X,
917                                         m_prop.visual_size.Y,
918                                         m_prop.visual_size.X));
919                         u8 li = m_last_light;
920                         setMeshColor(m_animated_meshnode->getMesh(), video::SColor(255,li,li,li));
921
922                         bool backface_culling = m_prop.backface_culling;
923                         if (m_is_player)
924                                 backface_culling = false;
925
926                         m_animated_meshnode->setMaterialFlag(video::EMF_LIGHTING, false);
927                         m_animated_meshnode->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
928                         m_animated_meshnode->setMaterialType(video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF);
929                         m_animated_meshnode->setMaterialFlag(video::EMF_FOG_ENABLE, true);
930                         m_animated_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING, backface_culling);
931                 }
932                 else
933                         errorstream<<"GenericCAO::addToScene(): Could not load mesh "<<m_prop.mesh<<std::endl;
934         }
935         else if(m_prop.visual == "wielditem") {
936                 infostream<<"GenericCAO::addToScene(): wielditem"<<std::endl;
937                 infostream<<"textures: "<<m_prop.textures.size()<<std::endl;
938                 if(m_prop.textures.size() >= 1){
939                         infostream<<"textures[0]: "<<m_prop.textures[0]<<std::endl;
940                         IItemDefManager *idef = m_client->idef();
941                         ItemStack item(m_prop.textures[0], 1, 0, "", idef);
942
943                         m_wield_meshnode = new WieldMeshSceneNode(
944                                         smgr->getRootSceneNode(), smgr, -1);
945                         m_wield_meshnode->setItem(item, m_client);
946
947                         m_wield_meshnode->setScale(v3f(m_prop.visual_size.X/2,
948                                         m_prop.visual_size.Y/2,
949                                         m_prop.visual_size.X/2));
950                         u8 li = m_last_light;
951                         m_wield_meshnode->setColor(video::SColor(255,li,li,li));
952                 }
953         } else {
954                 infostream<<"GenericCAO::addToScene(): \""<<m_prop.visual
955                                 <<"\" not supported"<<std::endl;
956         }
957
958         /* don't update while punch texture modifier is active */
959         if (m_reset_textures_timer < 0)
960                 updateTextures(m_current_texture_modifier);
961
962         scene::ISceneNode *node = getSceneNode();
963         if (node && m_prop.nametag != "" && !m_is_local_player) {
964                 // Add nametag
965                 m_nametag = m_client->getCamera()->addNametag(node,
966                         m_prop.nametag, m_prop.nametag_color);
967         }
968
969         updateNodePos();
970         updateAnimation();
971         updateBonePosition();
972         updateAttachments();
973 }
974
975 void GenericCAO::updateLight(u8 light_at_pos)
976 {
977         // Don't update light of attached one
978         if (getParent() != NULL) {
979                 return;
980         }
981
982         updateLightNoCheck(light_at_pos);
983
984         // Update light of all children
985         for (std::vector<u16>::size_type i = 0; i < m_children.size(); i++) {
986                 ClientActiveObject *obj = m_env->getActiveObject(m_children[i]);
987                 if (obj) {
988                         obj->updateLightNoCheck(light_at_pos);
989                 }
990         }
991 }
992
993 void GenericCAO::updateLightNoCheck(u8 light_at_pos)
994 {
995         u8 li = decode_light(light_at_pos);
996         if (li != m_last_light) {
997                 m_last_light = li;
998                 video::SColor color(255,li,li,li);
999                 if (m_meshnode) {
1000                         setMeshColor(m_meshnode->getMesh(), color);
1001                 } else if (m_animated_meshnode) {
1002                         setMeshColor(m_animated_meshnode->getMesh(), color);
1003                 } else if (m_wield_meshnode) {
1004                         m_wield_meshnode->setColor(color);
1005                 } else if (m_spritenode) {
1006                         m_spritenode->setColor(color);
1007                 }
1008         }
1009 }
1010
1011 v3s16 GenericCAO::getLightPosition()
1012 {
1013         return floatToInt(m_position, BS);
1014 }
1015
1016 void GenericCAO::updateNodePos()
1017 {
1018         if (getParent() != NULL)
1019                 return;
1020
1021         scene::ISceneNode *node = getSceneNode();
1022
1023         if (node) {
1024                 v3s16 camera_offset = m_env->getCameraOffset();
1025                 node->setPosition(pos_translator.vect_show - intToFloat(camera_offset, BS));
1026                 if (node != m_spritenode) { // rotate if not a sprite
1027                         v3f rot = node->getRotation();
1028                         rot.Y = -m_yaw;
1029                         node->setRotation(rot);
1030                 }
1031         }
1032 }
1033
1034 void GenericCAO::step(float dtime, ClientEnvironment *env)
1035 {
1036         // Handel model of local player instantly to prevent lags
1037         if(m_is_local_player)
1038         {
1039                 LocalPlayer *player = m_env->getLocalPlayer();
1040
1041                 if (m_is_visible)
1042                 {
1043                         int old_anim = player->last_animation;
1044                         float old_anim_speed = player->last_animation_speed;
1045                         m_position = player->getPosition() + v3f(0,BS,0);
1046                         m_velocity = v3f(0,0,0);
1047                         m_acceleration = v3f(0,0,0);
1048                         pos_translator.vect_show = m_position;
1049                         m_yaw = player->getYaw();
1050                         PlayerControl controls = player->getPlayerControl();
1051
1052                         bool walking = false;
1053                         if (controls.up || controls.down || controls.left || controls.right ||
1054                                         controls.forw_move_joystick_axis != 0.f ||
1055                                         controls.sidew_move_joystick_axis != 0.f)
1056                                 walking = true;
1057
1058                         f32 new_speed = player->local_animation_speed;
1059                         v2s32 new_anim = v2s32(0,0);
1060                         bool allow_update = false;
1061
1062                         // increase speed if using fast or flying fast
1063                         if((g_settings->getBool("fast_move") &&
1064                                         m_client->checkLocalPrivilege("fast")) &&
1065                                         (controls.aux1 ||
1066                                         (!player->touching_ground &&
1067                                         g_settings->getBool("free_move") &&
1068                                         m_client->checkLocalPrivilege("fly"))))
1069                                         new_speed *= 1.5;
1070                         // slowdown speed if sneeking
1071                         if(controls.sneak && walking)
1072                                 new_speed /= 2;
1073
1074                         if(walking && (controls.LMB || controls.RMB))
1075                         {
1076                                 new_anim = player->local_animations[3];
1077                                 player->last_animation = WD_ANIM;
1078                         } else if(walking) {
1079                                 new_anim = player->local_animations[1];
1080                                 player->last_animation = WALK_ANIM;
1081                         } else if(controls.LMB || controls.RMB) {
1082                                 new_anim = player->local_animations[2];
1083                                 player->last_animation = DIG_ANIM;
1084                         }
1085
1086                         // Apply animations if input detected and not attached
1087                         // or set idle animation
1088                         if ((new_anim.X + new_anim.Y) > 0 && !player->isAttached)
1089                         {
1090                                 allow_update = true;
1091                                 m_animation_range = new_anim;
1092                                 m_animation_speed = new_speed;
1093                                 player->last_animation_speed = m_animation_speed;
1094                         } else {
1095                                 player->last_animation = NO_ANIM;
1096
1097                                 if (old_anim != NO_ANIM)
1098                                 {
1099                                         m_animation_range = player->local_animations[0];
1100                                         updateAnimation();
1101                                 }
1102                         }
1103
1104                         // Update local player animations
1105                         if ((player->last_animation != old_anim ||
1106                                 m_animation_speed != old_anim_speed) &&
1107                                 player->last_animation != NO_ANIM && allow_update)
1108                                         updateAnimation();
1109
1110                 }
1111         }
1112
1113         if(m_visuals_expired && m_smgr && m_irr){
1114                 m_visuals_expired = false;
1115
1116                 // Attachments, part 1: All attached objects must be unparented first,
1117                 // or Irrlicht causes a segmentation fault
1118                 for(std::vector<u16>::iterator ci = m_children.begin();
1119                                 ci != m_children.end();)
1120                 {
1121                         if (m_env->attachement_parent_ids[*ci] != getId()) {
1122                                 ci = m_children.erase(ci);
1123                                 continue;
1124                         }
1125                         ClientActiveObject *obj = m_env->getActiveObject(*ci);
1126                         if (obj) {
1127                                 scene::ISceneNode *child_node = obj->getSceneNode();
1128                                 if (child_node)
1129                                         child_node->setParent(m_smgr->getRootSceneNode());
1130                         }
1131                         ++ci;
1132                 }
1133
1134                 removeFromScene(false);
1135                 addToScene(m_smgr, m_client->tsrc(), m_irr);
1136
1137                 // Attachments, part 2: Now that the parent has been refreshed, put its attachments back
1138                 for (std::vector<u16>::size_type i = 0; i < m_children.size(); i++) {
1139                         // Get the object of the child
1140                         ClientActiveObject *obj = m_env->getActiveObject(m_children[i]);
1141                         if (obj)
1142                                 obj->setAttachments();
1143                 }
1144         }
1145
1146         // Make sure m_is_visible is always applied
1147         scene::ISceneNode *node = getSceneNode();
1148         if (node)
1149                 node->setVisible(m_is_visible);
1150
1151         if(getParent() != NULL) // Attachments should be glued to their parent by Irrlicht
1152         {
1153                 // Set these for later
1154                 m_position = getPosition();
1155                 m_velocity = v3f(0,0,0);
1156                 m_acceleration = v3f(0,0,0);
1157                 pos_translator.vect_show = m_position;
1158
1159                 if(m_is_local_player) // Update local player attachment position
1160                 {
1161                         LocalPlayer *player = m_env->getLocalPlayer();
1162                         player->overridePosition = getParent()->getPosition();
1163                         m_env->getLocalPlayer()->parent = getParent();
1164                 }
1165         } else {
1166                 v3f lastpos = pos_translator.vect_show;
1167
1168                 if(m_prop.physical)
1169                 {
1170                         aabb3f box = m_prop.collisionbox;
1171                         box.MinEdge *= BS;
1172                         box.MaxEdge *= BS;
1173                         collisionMoveResult moveresult;
1174                         f32 pos_max_d = BS*0.125; // Distance per iteration
1175                         v3f p_pos = m_position;
1176                         v3f p_velocity = m_velocity;
1177                         moveresult = collisionMoveSimple(env,env->getGameDef(),
1178                                         pos_max_d, box, m_prop.stepheight, dtime,
1179                                         &p_pos, &p_velocity, m_acceleration,
1180                                         this, m_prop.collideWithObjects);
1181                         // Apply results
1182                         m_position = p_pos;
1183                         m_velocity = p_velocity;
1184
1185                         bool is_end_position = moveresult.collides;
1186                         pos_translator.update(m_position, is_end_position, dtime);
1187                         pos_translator.translate(dtime);
1188                         updateNodePos();
1189                 } else {
1190                         m_position += dtime * m_velocity + 0.5 * dtime * dtime * m_acceleration;
1191                         m_velocity += dtime * m_acceleration;
1192                         pos_translator.update(m_position, pos_translator.aim_is_end,
1193                                         pos_translator.anim_time);
1194                         pos_translator.translate(dtime);
1195                         updateNodePos();
1196                 }
1197
1198                 float moved = lastpos.getDistanceFrom(pos_translator.vect_show);
1199                 m_step_distance_counter += moved;
1200                 if(m_step_distance_counter > 1.5*BS)
1201                 {
1202                         m_step_distance_counter = 0;
1203                         if(!m_is_local_player && m_prop.makes_footstep_sound)
1204                         {
1205                                 INodeDefManager *ndef = m_client->ndef();
1206                                 v3s16 p = floatToInt(getPosition() + v3f(0,
1207                                                 (m_prop.collisionbox.MinEdge.Y-0.5)*BS, 0), BS);
1208                                 MapNode n = m_env->getMap().getNodeNoEx(p);
1209                                 SimpleSoundSpec spec = ndef->get(n).sound_footstep;
1210                                 m_client->sound()->playSoundAt(spec, false, getPosition());
1211                         }
1212                 }
1213         }
1214
1215         m_anim_timer += dtime;
1216         if(m_anim_timer >= m_anim_framelength)
1217         {
1218                 m_anim_timer -= m_anim_framelength;
1219                 m_anim_frame++;
1220                 if(m_anim_frame >= m_anim_num_frames)
1221                         m_anim_frame = 0;
1222         }
1223
1224         updateTexturePos();
1225
1226         if(m_reset_textures_timer >= 0)
1227         {
1228                 m_reset_textures_timer -= dtime;
1229                 if(m_reset_textures_timer <= 0) {
1230                         m_reset_textures_timer = -1;
1231                         updateTextures(m_previous_texture_modifier);
1232                 }
1233         }
1234         if(getParent() == NULL && fabs(m_prop.automatic_rotate) > 0.001)
1235         {
1236                 m_yaw += dtime * m_prop.automatic_rotate * 180 / M_PI;
1237                 updateNodePos();
1238         }
1239
1240         if (getParent() == NULL && m_prop.automatic_face_movement_dir &&
1241                         (fabs(m_velocity.Z) > 0.001 || fabs(m_velocity.X) > 0.001))
1242         {
1243                 float optimal_yaw = atan2(m_velocity.Z,m_velocity.X) * 180 / M_PI
1244                                 + m_prop.automatic_face_movement_dir_offset;
1245                 float max_rotation_delta =
1246                                 dtime * m_prop.automatic_face_movement_max_rotation_per_sec;
1247
1248                 if ((m_prop.automatic_face_movement_max_rotation_per_sec > 0) &&
1249                         (fabs(m_yaw - optimal_yaw) > max_rotation_delta)) {
1250
1251                         m_yaw = optimal_yaw < m_yaw ? m_yaw - max_rotation_delta : m_yaw + max_rotation_delta;
1252                 } else {
1253                         m_yaw = optimal_yaw;
1254                 }
1255                 updateNodePos();
1256         }
1257 }
1258
1259 void GenericCAO::updateTexturePos()
1260 {
1261         if(m_spritenode)
1262         {
1263                 scene::ICameraSceneNode* camera =
1264                                 m_spritenode->getSceneManager()->getActiveCamera();
1265                 if(!camera)
1266                         return;
1267                 v3f cam_to_entity = m_spritenode->getAbsolutePosition()
1268                                 - camera->getAbsolutePosition();
1269                 cam_to_entity.normalize();
1270
1271                 int row = m_tx_basepos.Y;
1272                 int col = m_tx_basepos.X;
1273
1274                 if(m_tx_select_horiz_by_yawpitch)
1275                 {
1276                         if(cam_to_entity.Y > 0.75)
1277                                 col += 5;
1278                         else if(cam_to_entity.Y < -0.75)
1279                                 col += 4;
1280                         else{
1281                                 float mob_dir =
1282                                                 atan2(cam_to_entity.Z, cam_to_entity.X) / M_PI * 180.;
1283                                 float dir = mob_dir - m_yaw;
1284                                 dir = wrapDegrees_180(dir);
1285                                 //infostream<<"id="<<m_id<<" dir="<<dir<<std::endl;
1286                                 if(fabs(wrapDegrees_180(dir - 0)) <= 45.1)
1287                                         col += 2;
1288                                 else if(fabs(wrapDegrees_180(dir - 90)) <= 45.1)
1289                                         col += 3;
1290                                 else if(fabs(wrapDegrees_180(dir - 180)) <= 45.1)
1291                                         col += 0;
1292                                 else if(fabs(wrapDegrees_180(dir + 90)) <= 45.1)
1293                                         col += 1;
1294                                 else
1295                                         col += 4;
1296                         }
1297                 }
1298
1299                 // Animation goes downwards
1300                 row += m_anim_frame;
1301
1302                 float txs = m_tx_size.X;
1303                 float tys = m_tx_size.Y;
1304                 setBillboardTextureMatrix(m_spritenode,
1305                                 txs, tys, col, row);
1306         }
1307 }
1308
1309 void GenericCAO::updateTextures(const std::string mod)
1310 {
1311         ITextureSource *tsrc = m_client->tsrc();
1312
1313         bool use_trilinear_filter = g_settings->getBool("trilinear_filter");
1314         bool use_bilinear_filter = g_settings->getBool("bilinear_filter");
1315         bool use_anisotropic_filter = g_settings->getBool("anisotropic_filter");
1316
1317         m_previous_texture_modifier = m_current_texture_modifier;
1318         m_current_texture_modifier = mod;
1319
1320         if(m_spritenode)
1321         {
1322                 if(m_prop.visual == "sprite")
1323                 {
1324                         std::string texturestring = "unknown_node.png";
1325                         if(m_prop.textures.size() >= 1)
1326                                 texturestring = m_prop.textures[0];
1327                         texturestring += mod;
1328                         m_spritenode->setMaterialTexture(0,
1329                                         tsrc->getTextureForMesh(texturestring));
1330
1331                         // This allows setting per-material colors. However, until a real lighting
1332                         // system is added, the code below will have no effect. Once MineTest
1333                         // has directional lighting, it should work automatically.
1334                         if(m_prop.colors.size() >= 1)
1335                         {
1336                                 m_spritenode->getMaterial(0).AmbientColor = m_prop.colors[0];
1337                                 m_spritenode->getMaterial(0).DiffuseColor = m_prop.colors[0];
1338                                 m_spritenode->getMaterial(0).SpecularColor = m_prop.colors[0];
1339                         }
1340
1341                         m_spritenode->getMaterial(0).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1342                         m_spritenode->getMaterial(0).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1343                         m_spritenode->getMaterial(0).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1344                 }
1345         }
1346         if(m_animated_meshnode)
1347         {
1348                 if(m_prop.visual == "mesh")
1349                 {
1350                         for (u32 i = 0; i < m_prop.textures.size() &&
1351                                         i < m_animated_meshnode->getMaterialCount(); ++i)
1352                         {
1353                                 std::string texturestring = m_prop.textures[i];
1354                                 if(texturestring == "")
1355                                         continue; // Empty texture string means don't modify that material
1356                                 texturestring += mod;
1357                                 video::ITexture* texture = tsrc->getTextureForMesh(texturestring);
1358                                 if(!texture)
1359                                 {
1360                                         errorstream<<"GenericCAO::updateTextures(): Could not load texture "<<texturestring<<std::endl;
1361                                         continue;
1362                                 }
1363
1364                                 // Set material flags and texture
1365                                 video::SMaterial& material = m_animated_meshnode->getMaterial(i);
1366                                 material.TextureLayer[0].Texture = texture;
1367                                 material.setFlag(video::EMF_LIGHTING, false);
1368                                 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1369
1370                                 m_animated_meshnode->getMaterial(i)
1371                                                 .setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1372                                 m_animated_meshnode->getMaterial(i)
1373                                                 .setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1374                                 m_animated_meshnode->getMaterial(i)
1375                                                 .setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1376                         }
1377                         for (u32 i = 0; i < m_prop.colors.size() &&
1378                         i < m_animated_meshnode->getMaterialCount(); ++i)
1379                         {
1380                                 // This allows setting per-material colors. However, until a real lighting
1381                                 // system is added, the code below will have no effect. Once MineTest
1382                                 // has directional lighting, it should work automatically.
1383                                 m_animated_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1384                                 m_animated_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1385                                 m_animated_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1386                         }
1387                 }
1388         }
1389         if(m_meshnode)
1390         {
1391                 if(m_prop.visual == "cube")
1392                 {
1393                         for (u32 i = 0; i < 6; ++i)
1394                         {
1395                                 std::string texturestring = "unknown_node.png";
1396                                 if(m_prop.textures.size() > i)
1397                                         texturestring = m_prop.textures[i];
1398                                 texturestring += mod;
1399
1400
1401                                 // Set material flags and texture
1402                                 video::SMaterial& material = m_meshnode->getMaterial(i);
1403                                 material.setFlag(video::EMF_LIGHTING, false);
1404                                 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1405                                 material.setTexture(0,
1406                                                 tsrc->getTextureForMesh(texturestring));
1407                                 material.getTextureMatrix(0).makeIdentity();
1408
1409                                 // This allows setting per-material colors. However, until a real lighting
1410                                 // system is added, the code below will have no effect. Once MineTest
1411                                 // has directional lighting, it should work automatically.
1412                                 if(m_prop.colors.size() > i)
1413                                 {
1414                                         m_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1415                                         m_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1416                                         m_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1417                                 }
1418
1419                                 m_meshnode->getMaterial(i).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1420                                 m_meshnode->getMaterial(i).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1421                                 m_meshnode->getMaterial(i).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1422                         }
1423                 }
1424                 else if(m_prop.visual == "upright_sprite")
1425                 {
1426                         scene::IMesh *mesh = m_meshnode->getMesh();
1427                         {
1428                                 std::string tname = "unknown_object.png";
1429                                 if(m_prop.textures.size() >= 1)
1430                                         tname = m_prop.textures[0];
1431                                 tname += mod;
1432                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(0);
1433                                 buf->getMaterial().setTexture(0,
1434                                                 tsrc->getTextureForMesh(tname));
1435
1436                                 // This allows setting per-material colors. However, until a real lighting
1437                                 // system is added, the code below will have no effect. Once MineTest
1438                                 // has directional lighting, it should work automatically.
1439                                 if(m_prop.colors.size() >= 1)
1440                                 {
1441                                         buf->getMaterial().AmbientColor = m_prop.colors[0];
1442                                         buf->getMaterial().DiffuseColor = m_prop.colors[0];
1443                                         buf->getMaterial().SpecularColor = m_prop.colors[0];
1444                                 }
1445
1446                                 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1447                                 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1448                                 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1449                         }
1450                         {
1451                                 std::string tname = "unknown_object.png";
1452                                 if(m_prop.textures.size() >= 2)
1453                                         tname = m_prop.textures[1];
1454                                 else if(m_prop.textures.size() >= 1)
1455                                         tname = m_prop.textures[0];
1456                                 tname += mod;
1457                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(1);
1458                                 buf->getMaterial().setTexture(0,
1459                                                 tsrc->getTextureForMesh(tname));
1460
1461                                 // This allows setting per-material colors. However, until a real lighting
1462                                 // system is added, the code below will have no effect. Once MineTest
1463                                 // has directional lighting, it should work automatically.
1464                                 if(m_prop.colors.size() >= 2)
1465                                 {
1466                                         buf->getMaterial().AmbientColor = m_prop.colors[1];
1467                                         buf->getMaterial().DiffuseColor = m_prop.colors[1];
1468                                         buf->getMaterial().SpecularColor = m_prop.colors[1];
1469                                 }
1470                                 else if(m_prop.colors.size() >= 1)
1471                                 {
1472                                         buf->getMaterial().AmbientColor = m_prop.colors[0];
1473                                         buf->getMaterial().DiffuseColor = m_prop.colors[0];
1474                                         buf->getMaterial().SpecularColor = m_prop.colors[0];
1475                                 }
1476
1477                                 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1478                                 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1479                                 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1480                         }
1481                 }
1482         }
1483 }
1484
1485 void GenericCAO::updateAnimation()
1486 {
1487         if(m_animated_meshnode == NULL)
1488                 return;
1489
1490         if (m_animated_meshnode->getStartFrame() != m_animation_range.X ||
1491                 m_animated_meshnode->getEndFrame() != m_animation_range.Y)
1492                         m_animated_meshnode->setFrameLoop(m_animation_range.X, m_animation_range.Y);
1493         if (m_animated_meshnode->getAnimationSpeed() != m_animation_speed)
1494                 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1495         m_animated_meshnode->setTransitionTime(m_animation_blend);
1496 // Requires Irrlicht 1.8 or greater
1497 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR > 1
1498         if (m_animated_meshnode->getLoopMode() != m_animation_loop)
1499                 m_animated_meshnode->setLoopMode(m_animation_loop);
1500 #endif
1501 }
1502
1503 void GenericCAO::updateBonePosition()
1504 {
1505         if(m_bone_position.empty() || m_animated_meshnode == NULL)
1506                 return;
1507
1508         m_animated_meshnode->setJointMode(irr::scene::EJUOR_CONTROL); // To write positions to the mesh on render
1509         for(UNORDERED_MAP<std::string, core::vector2d<v3f> >::const_iterator
1510                         ii = m_bone_position.begin(); ii != m_bone_position.end(); ++ii) {
1511                 std::string bone_name = (*ii).first;
1512                 v3f bone_pos = (*ii).second.X;
1513                 v3f bone_rot = (*ii).second.Y;
1514                 irr::scene::IBoneSceneNode* bone = m_animated_meshnode->getJointNode(bone_name.c_str());
1515                 if(bone)
1516                 {
1517                         bone->setPosition(bone_pos);
1518                         bone->setRotation(bone_rot);
1519                 }
1520         }
1521 }
1522
1523 void GenericCAO::updateAttachments()
1524 {
1525
1526         if (getParent() == NULL) { // Detach or don't attach
1527                 scene::ISceneNode *node = getSceneNode();
1528                 if (node) {
1529                         v3f old_position = node->getAbsolutePosition();
1530                         v3f old_rotation = node->getRotation();
1531                         node->setParent(m_smgr->getRootSceneNode());
1532                         node->setPosition(old_position);
1533                         node->setRotation(old_rotation);
1534                         node->updateAbsolutePosition();
1535                 }
1536                 if (m_is_local_player) {
1537                         LocalPlayer *player = m_env->getLocalPlayer();
1538                         player->isAttached = false;
1539                 }
1540         }
1541         else // Attach
1542         {
1543                 scene::ISceneNode *my_node = getSceneNode();
1544
1545                 scene::ISceneNode *parent_node = getParent()->getSceneNode();
1546                 scene::IAnimatedMeshSceneNode *parent_animated_mesh_node =
1547                                 getParent()->getAnimatedMeshSceneNode();
1548                 if (parent_animated_mesh_node && m_attachment_bone != "") {
1549                         parent_node = parent_animated_mesh_node->getJointNode(m_attachment_bone.c_str());
1550                 }
1551
1552                 if (my_node && parent_node) {
1553                         my_node->setParent(parent_node);
1554                         my_node->setPosition(m_attachment_position);
1555                         my_node->setRotation(m_attachment_rotation);
1556                         my_node->updateAbsolutePosition();
1557                 }
1558                 if (m_is_local_player) {
1559                         LocalPlayer *player = m_env->getLocalPlayer();
1560                         player->isAttached = true;
1561                 }
1562         }
1563 }
1564
1565 void GenericCAO::processMessage(const std::string &data)
1566 {
1567         //infostream<<"GenericCAO: Got message"<<std::endl;
1568         std::istringstream is(data, std::ios::binary);
1569         // command
1570         u8 cmd = readU8(is);
1571         if (cmd == GENERIC_CMD_SET_PROPERTIES) {
1572                 m_prop = gob_read_set_properties(is);
1573
1574                 m_selection_box = m_prop.collisionbox;
1575                 m_selection_box.MinEdge *= BS;
1576                 m_selection_box.MaxEdge *= BS;
1577
1578                 m_tx_size.X = 1.0 / m_prop.spritediv.X;
1579                 m_tx_size.Y = 1.0 / m_prop.spritediv.Y;
1580
1581                 if(!m_initial_tx_basepos_set){
1582                         m_initial_tx_basepos_set = true;
1583                         m_tx_basepos = m_prop.initial_sprite_basepos;
1584                 }
1585
1586                 if ((m_is_player && !m_is_local_player) && m_prop.nametag == "")
1587                         m_prop.nametag = m_name;
1588
1589                 expireVisuals();
1590         } else if (cmd == GENERIC_CMD_UPDATE_POSITION) {
1591                 // Not sent by the server if this object is an attachment.
1592                 // We might however get here if the server notices the object being detached before the client.
1593                 m_position = readV3F1000(is);
1594                 m_velocity = readV3F1000(is);
1595                 m_acceleration = readV3F1000(is);
1596                 if(fabs(m_prop.automatic_rotate) < 0.001)
1597                         m_yaw = readF1000(is);
1598                 else
1599                         readF1000(is);
1600                 bool do_interpolate = readU8(is);
1601                 bool is_end_position = readU8(is);
1602                 float update_interval = readF1000(is);
1603
1604                 // Place us a bit higher if we're physical, to not sink into
1605                 // the ground due to sucky collision detection...
1606                 if(m_prop.physical)
1607                         m_position += v3f(0,0.002,0);
1608
1609                 if(getParent() != NULL) // Just in case
1610                         return;
1611
1612                 if(do_interpolate)
1613                 {
1614                         if(!m_prop.physical)
1615                                 pos_translator.update(m_position, is_end_position, update_interval);
1616                 } else {
1617                         pos_translator.init(m_position);
1618                 }
1619                 updateNodePos();
1620         } else if (cmd == GENERIC_CMD_SET_TEXTURE_MOD) {
1621                 std::string mod = deSerializeString(is);
1622
1623                 // immediatly reset a engine issued texture modifier if a mod sends a different one
1624                 if (m_reset_textures_timer > 0) {
1625                         m_reset_textures_timer = -1;
1626                         updateTextures(m_previous_texture_modifier);
1627                 }
1628                 updateTextures(mod);
1629         } else if (cmd == GENERIC_CMD_SET_SPRITE) {
1630                 v2s16 p = readV2S16(is);
1631                 int num_frames = readU16(is);
1632                 float framelength = readF1000(is);
1633                 bool select_horiz_by_yawpitch = readU8(is);
1634
1635                 m_tx_basepos = p;
1636                 m_anim_num_frames = num_frames;
1637                 m_anim_framelength = framelength;
1638                 m_tx_select_horiz_by_yawpitch = select_horiz_by_yawpitch;
1639
1640                 updateTexturePos();
1641         } else if (cmd == GENERIC_CMD_SET_PHYSICS_OVERRIDE) {
1642                 float override_speed = readF1000(is);
1643                 float override_jump = readF1000(is);
1644                 float override_gravity = readF1000(is);
1645                 // these are sent inverted so we get true when the server sends nothing
1646                 bool sneak = !readU8(is);
1647                 bool sneak_glitch = !readU8(is);
1648
1649
1650                 if(m_is_local_player)
1651                 {
1652                         LocalPlayer *player = m_env->getLocalPlayer();
1653                         player->physics_override_speed = override_speed;
1654                         player->physics_override_jump = override_jump;
1655                         player->physics_override_gravity = override_gravity;
1656                         player->physics_override_sneak = sneak;
1657                         player->physics_override_sneak_glitch = sneak_glitch;
1658                 }
1659         } else if (cmd == GENERIC_CMD_SET_ANIMATION) {
1660                 // TODO: change frames send as v2s32 value
1661                 v2f range = readV2F1000(is);
1662                 if (!m_is_local_player) {
1663                         m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1664                         m_animation_speed = readF1000(is);
1665                         m_animation_blend = readF1000(is);
1666                         // these are sent inverted so we get true when the server sends nothing
1667                         m_animation_loop = !readU8(is);
1668                         updateAnimation();
1669                 } else {
1670                         LocalPlayer *player = m_env->getLocalPlayer();
1671                         if(player->last_animation == NO_ANIM)
1672                         {
1673                                 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1674                                 m_animation_speed = readF1000(is);
1675                                 m_animation_blend = readF1000(is);
1676                                 // these are sent inverted so we get true when the server sends nothing
1677                                 m_animation_loop = !readU8(is);
1678                         }
1679                         // update animation only if local animations present
1680                         // and received animation is unknown (except idle animation)
1681                         bool is_known = false;
1682                         for (int i = 1;i<4;i++)
1683                         {
1684                                 if(m_animation_range.Y == player->local_animations[i].Y)
1685                                         is_known = true;
1686                         }
1687                         if(!is_known ||
1688                                         (player->local_animations[1].Y + player->local_animations[2].Y < 1))
1689                         {
1690                                         updateAnimation();
1691                         }
1692                 }
1693         } else if (cmd == GENERIC_CMD_SET_BONE_POSITION) {
1694                 std::string bone = deSerializeString(is);
1695                 v3f position = readV3F1000(is);
1696                 v3f rotation = readV3F1000(is);
1697                 m_bone_position[bone] = core::vector2d<v3f>(position, rotation);
1698
1699                 updateBonePosition();
1700         } else if (cmd == GENERIC_CMD_ATTACH_TO) {
1701                 u16 parentID = readS16(is);
1702                 u16 oldparent = m_env->attachement_parent_ids[getId()];
1703                 if (oldparent) {
1704                         m_children.erase(std::remove(m_children.begin(), m_children.end(),
1705                                 getId()), m_children.end());
1706                 }
1707                 m_env->attachement_parent_ids[getId()] = parentID;
1708                 GenericCAO *parentobj = m_env->getGenericCAO(parentID);
1709
1710                 if (parentobj) {
1711                         parentobj->m_children.push_back(getId());
1712                 }
1713
1714                 m_attachment_bone = deSerializeString(is);
1715                 m_attachment_position = readV3F1000(is);
1716                 m_attachment_rotation = readV3F1000(is);
1717
1718                 // localplayer itself can't be attached to localplayer
1719                 if (!m_is_local_player) {
1720                         m_attached_to_local = getParent() != NULL && getParent()->isLocalPlayer();
1721                         // Objects attached to the local player should be hidden by default
1722                         m_is_visible = !m_attached_to_local;
1723                 }
1724
1725                 updateAttachments();
1726         } else if (cmd == GENERIC_CMD_PUNCHED) {
1727                 /*s16 damage =*/ readS16(is);
1728                 s16 result_hp = readS16(is);
1729
1730                 // Use this instead of the send damage to not interfere with prediction
1731                 s16 damage = m_hp - result_hp;
1732
1733                 m_hp = result_hp;
1734
1735                 if (damage > 0)
1736                 {
1737                         if (m_hp <= 0)
1738                         {
1739                                 // TODO: Execute defined fast response
1740                                 // As there is no definition, make a smoke puff
1741                                 ClientSimpleObject *simple = createSmokePuff(
1742                                                 m_smgr, m_env, m_position,
1743                                                 m_prop.visual_size * BS);
1744                                 m_env->addSimpleObject(simple);
1745                         } else {
1746                                 // TODO: Execute defined fast response
1747                                 // Flashing shall suffice as there is no definition
1748                                 m_reset_textures_timer = 0.05;
1749                                 if(damage >= 2)
1750                                         m_reset_textures_timer += 0.05 * damage;
1751                                 updateTextures(m_current_texture_modifier + "^[brighten");
1752                         }
1753                 }
1754         } else if (cmd == GENERIC_CMD_UPDATE_ARMOR_GROUPS) {
1755                 m_armor_groups.clear();
1756                 int armor_groups_size = readU16(is);
1757                 for(int i=0; i<armor_groups_size; i++)
1758                 {
1759                         std::string name = deSerializeString(is);
1760                         int rating = readS16(is);
1761                         m_armor_groups[name] = rating;
1762                 }
1763         } else if (cmd == GENERIC_CMD_UPDATE_NAMETAG_ATTRIBUTES) {
1764                 // Deprecated, for backwards compatibility only.
1765                 readU8(is); // version
1766                 m_prop.nametag_color = readARGB8(is);
1767                 if (m_nametag != NULL) {
1768                         m_nametag->nametag_color = m_prop.nametag_color;
1769                 }
1770         } else if (cmd == GENERIC_CMD_SPAWN_INFANT) {
1771                 u16 child_id = readU16(is);
1772                 u8 type = readU8(is);
1773
1774                 if (GenericCAO *childobj = m_env->getGenericCAO(child_id)) {
1775                         childobj->processInitData(deSerializeLongString(is));
1776                 } else {
1777                         m_env->addActiveObject(child_id, type, deSerializeLongString(is));
1778                 }
1779         } else {
1780                 warningstream << FUNCTION_NAME
1781                         << ": unknown command or outdated client \""
1782                         << cmd << std::endl;
1783         }
1784 }
1785
1786 /* \pre punchitem != NULL
1787  */
1788 bool GenericCAO::directReportPunch(v3f dir, const ItemStack *punchitem,
1789                 float time_from_last_punch)
1790 {
1791         assert(punchitem);      // pre-condition
1792         const ToolCapabilities *toolcap =
1793                         &punchitem->getToolCapabilities(m_client->idef());
1794         PunchDamageResult result = getPunchDamage(
1795                         m_armor_groups,
1796                         toolcap,
1797                         punchitem,
1798                         time_from_last_punch);
1799
1800         if(result.did_punch && result.damage != 0)
1801         {
1802                 if(result.damage < m_hp)
1803                 {
1804                         m_hp -= result.damage;
1805                 } else {
1806                         m_hp = 0;
1807                         // TODO: Execute defined fast response
1808                         // As there is no definition, make a smoke puff
1809                         ClientSimpleObject *simple = createSmokePuff(
1810                                         m_smgr, m_env, m_position,
1811                                         m_prop.visual_size * BS);
1812                         m_env->addSimpleObject(simple);
1813                 }
1814                 // TODO: Execute defined fast response
1815                 // Flashing shall suffice as there is no definition
1816                 m_reset_textures_timer = 0.05;
1817                 if(result.damage >= 2)
1818                         m_reset_textures_timer += 0.05 * result.damage;
1819                 updateTextures(m_current_texture_modifier + "^[brighten");
1820         }
1821
1822         return false;
1823 }
1824
1825 std::string GenericCAO::debugInfoText()
1826 {
1827         std::ostringstream os(std::ios::binary);
1828         os<<"GenericCAO hp="<<m_hp<<"\n";
1829         os<<"armor={";
1830         for(ItemGroupList::const_iterator i = m_armor_groups.begin();
1831                         i != m_armor_groups.end(); ++i)
1832         {
1833                 os<<i->first<<"="<<i->second<<", ";
1834         }
1835         os<<"}";
1836         return os.str();
1837 }
1838
1839 // Prototype
1840 GenericCAO proto_GenericCAO(NULL, NULL);