Make the player collisionbox settable
[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                 ItemStack item;
937                 infostream << "GenericCAO::addToScene(): wielditem" << std::endl;
938                 if (m_prop.wield_item == "") {
939                         // Old format, only textures are specified.
940                         infostream << "textures: " << m_prop.textures.size() << std::endl;
941                         if (m_prop.textures.size() >= 1) {
942                                 infostream << "textures[0]: " << m_prop.textures[0]
943                                         << std::endl;
944                                 IItemDefManager *idef = m_client->idef();
945                                 item = ItemStack(m_prop.textures[0], 1, 0, idef);
946                         }
947                 } else {
948                         infostream << "serialized form: " << m_prop.wield_item << std::endl;
949                         item.deSerialize(m_prop.wield_item, m_client->idef());
950                 }
951                 m_wield_meshnode = new WieldMeshSceneNode(smgr->getRootSceneNode(),
952                         smgr, -1);
953                 m_wield_meshnode->setItem(item, m_client);
954
955                 m_wield_meshnode->setScale(
956                         v3f(m_prop.visual_size.X / 2, m_prop.visual_size.Y / 2,
957                                 m_prop.visual_size.X / 2));
958                 u8 li = m_last_light;
959                 m_wield_meshnode->setColor(video::SColor(255, li, li, li));
960         } else {
961                 infostream<<"GenericCAO::addToScene(): \""<<m_prop.visual
962                                 <<"\" not supported"<<std::endl;
963         }
964
965         /* don't update while punch texture modifier is active */
966         if (m_reset_textures_timer < 0)
967                 updateTextures(m_current_texture_modifier);
968
969         scene::ISceneNode *node = getSceneNode();
970         if (node && m_prop.nametag != "" && !m_is_local_player) {
971                 // Add nametag
972                 m_nametag = m_client->getCamera()->addNametag(node,
973                         m_prop.nametag, m_prop.nametag_color);
974         }
975
976         updateNodePos();
977         updateAnimation();
978         updateBonePosition();
979         updateAttachments();
980 }
981
982 void GenericCAO::updateLight(u8 light_at_pos)
983 {
984         // Don't update light of attached one
985         if (getParent() != NULL) {
986                 return;
987         }
988
989         updateLightNoCheck(light_at_pos);
990
991         // Update light of all children
992         for (std::vector<u16>::size_type i = 0; i < m_children.size(); i++) {
993                 ClientActiveObject *obj = m_env->getActiveObject(m_children[i]);
994                 if (obj) {
995                         obj->updateLightNoCheck(light_at_pos);
996                 }
997         }
998 }
999
1000 void GenericCAO::updateLightNoCheck(u8 light_at_pos)
1001 {
1002         u8 li = decode_light(light_at_pos);
1003         if (li != m_last_light) {
1004                 m_last_light = li;
1005                 video::SColor color(255,li,li,li);
1006                 if (m_meshnode) {
1007                         setMeshColor(m_meshnode->getMesh(), color);
1008                 } else if (m_animated_meshnode) {
1009                         setMeshColor(m_animated_meshnode->getMesh(), color);
1010                 } else if (m_wield_meshnode) {
1011                         m_wield_meshnode->setColor(color);
1012                 } else if (m_spritenode) {
1013                         m_spritenode->setColor(color);
1014                 }
1015         }
1016 }
1017
1018 v3s16 GenericCAO::getLightPosition()
1019 {
1020         return floatToInt(m_position, BS);
1021 }
1022
1023 void GenericCAO::updateNodePos()
1024 {
1025         if (getParent() != NULL)
1026                 return;
1027
1028         scene::ISceneNode *node = getSceneNode();
1029
1030         if (node) {
1031                 v3s16 camera_offset = m_env->getCameraOffset();
1032                 node->setPosition(pos_translator.vect_show - intToFloat(camera_offset, BS));
1033                 if (node != m_spritenode) { // rotate if not a sprite
1034                         v3f rot = node->getRotation();
1035                         rot.Y = -m_yaw;
1036                         node->setRotation(rot);
1037                 }
1038         }
1039 }
1040
1041 void GenericCAO::step(float dtime, ClientEnvironment *env)
1042 {
1043         // Handel model of local player instantly to prevent lags
1044         if (m_is_local_player) {
1045                 LocalPlayer *player = m_env->getLocalPlayer();
1046                 if (m_is_visible) {
1047                         int old_anim = player->last_animation;
1048                         float old_anim_speed = player->last_animation_speed;
1049                         m_position = player->getPosition() + v3f(0,BS,0);
1050                         m_velocity = v3f(0,0,0);
1051                         m_acceleration = v3f(0,0,0);
1052                         pos_translator.vect_show = m_position;
1053                         m_yaw = player->getYaw();
1054                         const PlayerControl &controls = player->getPlayerControl();
1055
1056                         bool walking = false;
1057                         if (controls.up || controls.down || controls.left || controls.right ||
1058                                         controls.forw_move_joystick_axis != 0.f ||
1059                                         controls.sidew_move_joystick_axis != 0.f)
1060                                 walking = true;
1061
1062                         f32 new_speed = player->local_animation_speed;
1063                         v2s32 new_anim = v2s32(0,0);
1064                         bool allow_update = false;
1065
1066                         // increase speed if using fast or flying fast
1067                         if((g_settings->getBool("fast_move") &&
1068                                         m_client->checkLocalPrivilege("fast")) &&
1069                                         (controls.aux1 ||
1070                                         (!player->touching_ground &&
1071                                         g_settings->getBool("free_move") &&
1072                                         m_client->checkLocalPrivilege("fly"))))
1073                                         new_speed *= 1.5;
1074                         // slowdown speed if sneeking
1075                         if (controls.sneak && walking)
1076                                 new_speed /= 2;
1077
1078                         if (walking && (controls.LMB || controls.RMB)) {
1079                                 new_anim = player->local_animations[3];
1080                                 player->last_animation = WD_ANIM;
1081                         } else if(walking) {
1082                                 new_anim = player->local_animations[1];
1083                                 player->last_animation = WALK_ANIM;
1084                         } else if(controls.LMB || controls.RMB) {
1085                                 new_anim = player->local_animations[2];
1086                                 player->last_animation = DIG_ANIM;
1087                         }
1088
1089                         // Apply animations if input detected and not attached
1090                         // or set idle animation
1091                         if ((new_anim.X + new_anim.Y) > 0 && !player->isAttached) {
1092                                 allow_update = true;
1093                                 m_animation_range = new_anim;
1094                                 m_animation_speed = new_speed;
1095                                 player->last_animation_speed = m_animation_speed;
1096                         } else {
1097                                 player->last_animation = NO_ANIM;
1098
1099                                 if (old_anim != NO_ANIM) {
1100                                         m_animation_range = player->local_animations[0];
1101                                         updateAnimation();
1102                                 }
1103                         }
1104
1105                         // Update local player animations
1106                         if ((player->last_animation != old_anim ||
1107                                 m_animation_speed != old_anim_speed) &&
1108                                 player->last_animation != NO_ANIM && allow_update)
1109                                         updateAnimation();
1110
1111                 }
1112         }
1113
1114         if(m_visuals_expired && m_smgr && m_irr){
1115                 m_visuals_expired = false;
1116
1117                 // Attachments, part 1: All attached objects must be unparented first,
1118                 // or Irrlicht causes a segmentation fault
1119                 for(std::vector<u16>::iterator ci = m_children.begin();
1120                                 ci != m_children.end();)
1121                 {
1122                         if (m_env->attachement_parent_ids[*ci] != getId()) {
1123                                 ci = m_children.erase(ci);
1124                                 continue;
1125                         }
1126                         ClientActiveObject *obj = m_env->getActiveObject(*ci);
1127                         if (obj) {
1128                                 scene::ISceneNode *child_node = obj->getSceneNode();
1129                                 if (child_node)
1130                                         child_node->setParent(m_smgr->getRootSceneNode());
1131                         }
1132                         ++ci;
1133                 }
1134
1135                 removeFromScene(false);
1136                 addToScene(m_smgr, m_client->tsrc(), m_irr);
1137
1138                 // Attachments, part 2: Now that the parent has been refreshed, put its attachments back
1139                 for (std::vector<u16>::size_type i = 0; i < m_children.size(); i++) {
1140                         // Get the object of the child
1141                         ClientActiveObject *obj = m_env->getActiveObject(m_children[i]);
1142                         if (obj)
1143                                 obj->setAttachments();
1144                 }
1145         }
1146
1147         // Make sure m_is_visible is always applied
1148         scene::ISceneNode *node = getSceneNode();
1149         if (node)
1150                 node->setVisible(m_is_visible);
1151
1152         if(getParent() != NULL) // Attachments should be glued to their parent by Irrlicht
1153         {
1154                 // Set these for later
1155                 m_position = getPosition();
1156                 m_velocity = v3f(0,0,0);
1157                 m_acceleration = v3f(0,0,0);
1158                 pos_translator.vect_show = m_position;
1159
1160                 if(m_is_local_player) // Update local player attachment position
1161                 {
1162                         LocalPlayer *player = m_env->getLocalPlayer();
1163                         player->overridePosition = getParent()->getPosition();
1164                         m_env->getLocalPlayer()->parent = getParent();
1165                 }
1166         } else {
1167                 v3f lastpos = pos_translator.vect_show;
1168
1169                 if(m_prop.physical)
1170                 {
1171                         aabb3f box = m_prop.collisionbox;
1172                         box.MinEdge *= BS;
1173                         box.MaxEdge *= BS;
1174                         collisionMoveResult moveresult;
1175                         f32 pos_max_d = BS*0.125; // Distance per iteration
1176                         v3f p_pos = m_position;
1177                         v3f p_velocity = m_velocity;
1178                         moveresult = collisionMoveSimple(env,env->getGameDef(),
1179                                         pos_max_d, box, m_prop.stepheight, dtime,
1180                                         &p_pos, &p_velocity, m_acceleration,
1181                                         this, m_prop.collideWithObjects);
1182                         // Apply results
1183                         m_position = p_pos;
1184                         m_velocity = p_velocity;
1185
1186                         bool is_end_position = moveresult.collides;
1187                         pos_translator.update(m_position, is_end_position, dtime);
1188                         pos_translator.translate(dtime);
1189                         updateNodePos();
1190                 } else {
1191                         m_position += dtime * m_velocity + 0.5 * dtime * dtime * m_acceleration;
1192                         m_velocity += dtime * m_acceleration;
1193                         pos_translator.update(m_position, pos_translator.aim_is_end,
1194                                         pos_translator.anim_time);
1195                         pos_translator.translate(dtime);
1196                         updateNodePos();
1197                 }
1198
1199                 float moved = lastpos.getDistanceFrom(pos_translator.vect_show);
1200                 m_step_distance_counter += moved;
1201                 if(m_step_distance_counter > 1.5*BS)
1202                 {
1203                         m_step_distance_counter = 0;
1204                         if(!m_is_local_player && m_prop.makes_footstep_sound)
1205                         {
1206                                 INodeDefManager *ndef = m_client->ndef();
1207                                 v3s16 p = floatToInt(getPosition() + v3f(0,
1208                                                 (m_prop.collisionbox.MinEdge.Y-0.5)*BS, 0), BS);
1209                                 MapNode n = m_env->getMap().getNodeNoEx(p);
1210                                 SimpleSoundSpec spec = ndef->get(n).sound_footstep;
1211                                 m_client->sound()->playSoundAt(spec, false, getPosition());
1212                         }
1213                 }
1214         }
1215
1216         m_anim_timer += dtime;
1217         if(m_anim_timer >= m_anim_framelength)
1218         {
1219                 m_anim_timer -= m_anim_framelength;
1220                 m_anim_frame++;
1221                 if(m_anim_frame >= m_anim_num_frames)
1222                         m_anim_frame = 0;
1223         }
1224
1225         updateTexturePos();
1226
1227         if(m_reset_textures_timer >= 0)
1228         {
1229                 m_reset_textures_timer -= dtime;
1230                 if(m_reset_textures_timer <= 0) {
1231                         m_reset_textures_timer = -1;
1232                         updateTextures(m_previous_texture_modifier);
1233                 }
1234         }
1235         if(getParent() == NULL && fabs(m_prop.automatic_rotate) > 0.001)
1236         {
1237                 m_yaw += dtime * m_prop.automatic_rotate * 180 / M_PI;
1238                 updateNodePos();
1239         }
1240
1241         if (getParent() == NULL && m_prop.automatic_face_movement_dir &&
1242                         (fabs(m_velocity.Z) > 0.001 || fabs(m_velocity.X) > 0.001))
1243         {
1244                 float optimal_yaw = atan2(m_velocity.Z,m_velocity.X) * 180 / M_PI
1245                                 + m_prop.automatic_face_movement_dir_offset;
1246                 float max_rotation_delta =
1247                                 dtime * m_prop.automatic_face_movement_max_rotation_per_sec;
1248
1249                 if ((m_prop.automatic_face_movement_max_rotation_per_sec > 0) &&
1250                         (fabs(m_yaw - optimal_yaw) > max_rotation_delta)) {
1251
1252                         m_yaw = optimal_yaw < m_yaw ? m_yaw - max_rotation_delta : m_yaw + max_rotation_delta;
1253                 } else {
1254                         m_yaw = optimal_yaw;
1255                 }
1256                 updateNodePos();
1257         }
1258 }
1259
1260 void GenericCAO::updateTexturePos()
1261 {
1262         if(m_spritenode)
1263         {
1264                 scene::ICameraSceneNode* camera =
1265                                 m_spritenode->getSceneManager()->getActiveCamera();
1266                 if(!camera)
1267                         return;
1268                 v3f cam_to_entity = m_spritenode->getAbsolutePosition()
1269                                 - camera->getAbsolutePosition();
1270                 cam_to_entity.normalize();
1271
1272                 int row = m_tx_basepos.Y;
1273                 int col = m_tx_basepos.X;
1274
1275                 if(m_tx_select_horiz_by_yawpitch)
1276                 {
1277                         if(cam_to_entity.Y > 0.75)
1278                                 col += 5;
1279                         else if(cam_to_entity.Y < -0.75)
1280                                 col += 4;
1281                         else{
1282                                 float mob_dir =
1283                                                 atan2(cam_to_entity.Z, cam_to_entity.X) / M_PI * 180.;
1284                                 float dir = mob_dir - m_yaw;
1285                                 dir = wrapDegrees_180(dir);
1286                                 //infostream<<"id="<<m_id<<" dir="<<dir<<std::endl;
1287                                 if(fabs(wrapDegrees_180(dir - 0)) <= 45.1)
1288                                         col += 2;
1289                                 else if(fabs(wrapDegrees_180(dir - 90)) <= 45.1)
1290                                         col += 3;
1291                                 else if(fabs(wrapDegrees_180(dir - 180)) <= 45.1)
1292                                         col += 0;
1293                                 else if(fabs(wrapDegrees_180(dir + 90)) <= 45.1)
1294                                         col += 1;
1295                                 else
1296                                         col += 4;
1297                         }
1298                 }
1299
1300                 // Animation goes downwards
1301                 row += m_anim_frame;
1302
1303                 float txs = m_tx_size.X;
1304                 float tys = m_tx_size.Y;
1305                 setBillboardTextureMatrix(m_spritenode,
1306                                 txs, tys, col, row);
1307         }
1308 }
1309
1310 void GenericCAO::updateTextures(std::string mod)
1311 {
1312         ITextureSource *tsrc = m_client->tsrc();
1313
1314         bool use_trilinear_filter = g_settings->getBool("trilinear_filter");
1315         bool use_bilinear_filter = g_settings->getBool("bilinear_filter");
1316         bool use_anisotropic_filter = g_settings->getBool("anisotropic_filter");
1317
1318         m_previous_texture_modifier = m_current_texture_modifier;
1319         m_current_texture_modifier = mod;
1320
1321         if(m_spritenode)
1322         {
1323                 if(m_prop.visual == "sprite")
1324                 {
1325                         std::string texturestring = "unknown_node.png";
1326                         if(m_prop.textures.size() >= 1)
1327                                 texturestring = m_prop.textures[0];
1328                         texturestring += mod;
1329                         m_spritenode->setMaterialTexture(0,
1330                                         tsrc->getTextureForMesh(texturestring));
1331
1332                         // This allows setting per-material colors. However, until a real lighting
1333                         // system is added, the code below will have no effect. Once MineTest
1334                         // has directional lighting, it should work automatically.
1335                         if(m_prop.colors.size() >= 1)
1336                         {
1337                                 m_spritenode->getMaterial(0).AmbientColor = m_prop.colors[0];
1338                                 m_spritenode->getMaterial(0).DiffuseColor = m_prop.colors[0];
1339                                 m_spritenode->getMaterial(0).SpecularColor = m_prop.colors[0];
1340                         }
1341
1342                         m_spritenode->getMaterial(0).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1343                         m_spritenode->getMaterial(0).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1344                         m_spritenode->getMaterial(0).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1345                 }
1346         }
1347         if(m_animated_meshnode)
1348         {
1349                 if(m_prop.visual == "mesh")
1350                 {
1351                         for (u32 i = 0; i < m_prop.textures.size() &&
1352                                         i < m_animated_meshnode->getMaterialCount(); ++i)
1353                         {
1354                                 std::string texturestring = m_prop.textures[i];
1355                                 if(texturestring == "")
1356                                         continue; // Empty texture string means don't modify that material
1357                                 texturestring += mod;
1358                                 video::ITexture* texture = tsrc->getTextureForMesh(texturestring);
1359                                 if(!texture)
1360                                 {
1361                                         errorstream<<"GenericCAO::updateTextures(): Could not load texture "<<texturestring<<std::endl;
1362                                         continue;
1363                                 }
1364
1365                                 // Set material flags and texture
1366                                 video::SMaterial& material = m_animated_meshnode->getMaterial(i);
1367                                 material.TextureLayer[0].Texture = texture;
1368                                 material.setFlag(video::EMF_LIGHTING, false);
1369                                 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1370
1371                                 m_animated_meshnode->getMaterial(i)
1372                                                 .setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1373                                 m_animated_meshnode->getMaterial(i)
1374                                                 .setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1375                                 m_animated_meshnode->getMaterial(i)
1376                                                 .setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1377                         }
1378                         for (u32 i = 0; i < m_prop.colors.size() &&
1379                         i < m_animated_meshnode->getMaterialCount(); ++i)
1380                         {
1381                                 // This allows setting per-material colors. However, until a real lighting
1382                                 // system is added, the code below will have no effect. Once MineTest
1383                                 // has directional lighting, it should work automatically.
1384                                 m_animated_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1385                                 m_animated_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1386                                 m_animated_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1387                         }
1388                 }
1389         }
1390         if(m_meshnode)
1391         {
1392                 if(m_prop.visual == "cube")
1393                 {
1394                         for (u32 i = 0; i < 6; ++i)
1395                         {
1396                                 std::string texturestring = "unknown_node.png";
1397                                 if(m_prop.textures.size() > i)
1398                                         texturestring = m_prop.textures[i];
1399                                 texturestring += mod;
1400
1401
1402                                 // Set material flags and texture
1403                                 video::SMaterial& material = m_meshnode->getMaterial(i);
1404                                 material.setFlag(video::EMF_LIGHTING, false);
1405                                 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1406                                 material.setTexture(0,
1407                                                 tsrc->getTextureForMesh(texturestring));
1408                                 material.getTextureMatrix(0).makeIdentity();
1409
1410                                 // This allows setting per-material colors. However, until a real lighting
1411                                 // system is added, the code below will have no effect. Once MineTest
1412                                 // has directional lighting, it should work automatically.
1413                                 if(m_prop.colors.size() > i)
1414                                 {
1415                                         m_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1416                                         m_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1417                                         m_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1418                                 }
1419
1420                                 m_meshnode->getMaterial(i).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1421                                 m_meshnode->getMaterial(i).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1422                                 m_meshnode->getMaterial(i).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1423                         }
1424                 }
1425                 else if(m_prop.visual == "upright_sprite")
1426                 {
1427                         scene::IMesh *mesh = m_meshnode->getMesh();
1428                         {
1429                                 std::string tname = "unknown_object.png";
1430                                 if(m_prop.textures.size() >= 1)
1431                                         tname = m_prop.textures[0];
1432                                 tname += mod;
1433                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(0);
1434                                 buf->getMaterial().setTexture(0,
1435                                                 tsrc->getTextureForMesh(tname));
1436
1437                                 // This allows setting per-material colors. However, until a real lighting
1438                                 // system is added, the code below will have no effect. Once MineTest
1439                                 // has directional lighting, it should work automatically.
1440                                 if(m_prop.colors.size() >= 1)
1441                                 {
1442                                         buf->getMaterial().AmbientColor = m_prop.colors[0];
1443                                         buf->getMaterial().DiffuseColor = m_prop.colors[0];
1444                                         buf->getMaterial().SpecularColor = m_prop.colors[0];
1445                                 }
1446
1447                                 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1448                                 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1449                                 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1450                         }
1451                         {
1452                                 std::string tname = "unknown_object.png";
1453                                 if(m_prop.textures.size() >= 2)
1454                                         tname = m_prop.textures[1];
1455                                 else if(m_prop.textures.size() >= 1)
1456                                         tname = m_prop.textures[0];
1457                                 tname += mod;
1458                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(1);
1459                                 buf->getMaterial().setTexture(0,
1460                                                 tsrc->getTextureForMesh(tname));
1461
1462                                 // This allows setting per-material colors. However, until a real lighting
1463                                 // system is added, the code below will have no effect. Once MineTest
1464                                 // has directional lighting, it should work automatically.
1465                                 if(m_prop.colors.size() >= 2)
1466                                 {
1467                                         buf->getMaterial().AmbientColor = m_prop.colors[1];
1468                                         buf->getMaterial().DiffuseColor = m_prop.colors[1];
1469                                         buf->getMaterial().SpecularColor = m_prop.colors[1];
1470                                 }
1471                                 else if(m_prop.colors.size() >= 1)
1472                                 {
1473                                         buf->getMaterial().AmbientColor = m_prop.colors[0];
1474                                         buf->getMaterial().DiffuseColor = m_prop.colors[0];
1475                                         buf->getMaterial().SpecularColor = m_prop.colors[0];
1476                                 }
1477
1478                                 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1479                                 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1480                                 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1481                         }
1482                 }
1483         }
1484 }
1485
1486 void GenericCAO::updateAnimation()
1487 {
1488         if(m_animated_meshnode == NULL)
1489                 return;
1490
1491         if (m_animated_meshnode->getStartFrame() != m_animation_range.X ||
1492                 m_animated_meshnode->getEndFrame() != m_animation_range.Y)
1493                         m_animated_meshnode->setFrameLoop(m_animation_range.X, m_animation_range.Y);
1494         if (m_animated_meshnode->getAnimationSpeed() != m_animation_speed)
1495                 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1496         m_animated_meshnode->setTransitionTime(m_animation_blend);
1497 // Requires Irrlicht 1.8 or greater
1498 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR > 1
1499         if (m_animated_meshnode->getLoopMode() != m_animation_loop)
1500                 m_animated_meshnode->setLoopMode(m_animation_loop);
1501 #endif
1502 }
1503
1504 void GenericCAO::updateBonePosition()
1505 {
1506         if(m_bone_position.empty() || m_animated_meshnode == NULL)
1507                 return;
1508
1509         m_animated_meshnode->setJointMode(irr::scene::EJUOR_CONTROL); // To write positions to the mesh on render
1510         for(UNORDERED_MAP<std::string, core::vector2d<v3f> >::const_iterator
1511                         ii = m_bone_position.begin(); ii != m_bone_position.end(); ++ii) {
1512                 std::string bone_name = (*ii).first;
1513                 v3f bone_pos = (*ii).second.X;
1514                 v3f bone_rot = (*ii).second.Y;
1515                 irr::scene::IBoneSceneNode* bone = m_animated_meshnode->getJointNode(bone_name.c_str());
1516                 if(bone)
1517                 {
1518                         bone->setPosition(bone_pos);
1519                         bone->setRotation(bone_rot);
1520                 }
1521         }
1522 }
1523
1524 void GenericCAO::updateAttachments()
1525 {
1526
1527         if (getParent() == NULL) { // Detach or don't attach
1528                 scene::ISceneNode *node = getSceneNode();
1529                 if (node) {
1530                         v3f old_position = node->getAbsolutePosition();
1531                         v3f old_rotation = node->getRotation();
1532                         node->setParent(m_smgr->getRootSceneNode());
1533                         node->setPosition(old_position);
1534                         node->setRotation(old_rotation);
1535                         node->updateAbsolutePosition();
1536                 }
1537                 if (m_is_local_player) {
1538                         LocalPlayer *player = m_env->getLocalPlayer();
1539                         player->isAttached = false;
1540                 }
1541         }
1542         else // Attach
1543         {
1544                 scene::ISceneNode *my_node = getSceneNode();
1545
1546                 scene::ISceneNode *parent_node = getParent()->getSceneNode();
1547                 scene::IAnimatedMeshSceneNode *parent_animated_mesh_node =
1548                                 getParent()->getAnimatedMeshSceneNode();
1549                 if (parent_animated_mesh_node && m_attachment_bone != "") {
1550                         parent_node = parent_animated_mesh_node->getJointNode(m_attachment_bone.c_str());
1551                 }
1552
1553                 if (my_node && parent_node) {
1554                         my_node->setParent(parent_node);
1555                         my_node->setPosition(m_attachment_position);
1556                         my_node->setRotation(m_attachment_rotation);
1557                         my_node->updateAbsolutePosition();
1558                 }
1559                 if (m_is_local_player) {
1560                         LocalPlayer *player = m_env->getLocalPlayer();
1561                         player->isAttached = true;
1562                 }
1563         }
1564 }
1565
1566 void GenericCAO::processMessage(const std::string &data)
1567 {
1568         //infostream<<"GenericCAO: Got message"<<std::endl;
1569         std::istringstream is(data, std::ios::binary);
1570         // command
1571         u8 cmd = readU8(is);
1572         if (cmd == GENERIC_CMD_SET_PROPERTIES) {
1573                 m_prop = gob_read_set_properties(is);
1574
1575                 m_selection_box = m_prop.collisionbox;
1576                 m_selection_box.MinEdge *= BS;
1577                 m_selection_box.MaxEdge *= BS;
1578
1579                 m_tx_size.X = 1.0 / m_prop.spritediv.X;
1580                 m_tx_size.Y = 1.0 / m_prop.spritediv.Y;
1581
1582                 if(!m_initial_tx_basepos_set){
1583                         m_initial_tx_basepos_set = true;
1584                         m_tx_basepos = m_prop.initial_sprite_basepos;
1585                 }
1586                 if (m_is_local_player) {
1587                         LocalPlayer *player = m_env->getLocalPlayer();
1588
1589                         player->makes_footstep_sound = m_prop.makes_footstep_sound;
1590
1591                         aabb3f collisionbox = m_selection_box;
1592                         collisionbox.MinEdge += v3f(0, BS, 0);
1593                         collisionbox.MaxEdge += v3f(0, BS, 0);
1594                         player->setCollisionbox(collisionbox);
1595                 }
1596
1597                 if ((m_is_player && !m_is_local_player) && m_prop.nametag == "")
1598                         m_prop.nametag = m_name;
1599
1600                 expireVisuals();
1601         } else if (cmd == GENERIC_CMD_UPDATE_POSITION) {
1602                 // Not sent by the server if this object is an attachment.
1603                 // We might however get here if the server notices the object being detached before the client.
1604                 m_position = readV3F1000(is);
1605                 m_velocity = readV3F1000(is);
1606                 m_acceleration = readV3F1000(is);
1607                 if(fabs(m_prop.automatic_rotate) < 0.001)
1608                         m_yaw = readF1000(is);
1609                 else
1610                         readF1000(is);
1611                 bool do_interpolate = readU8(is);
1612                 bool is_end_position = readU8(is);
1613                 float update_interval = readF1000(is);
1614
1615                 // Place us a bit higher if we're physical, to not sink into
1616                 // the ground due to sucky collision detection...
1617                 if(m_prop.physical)
1618                         m_position += v3f(0,0.002,0);
1619
1620                 if(getParent() != NULL) // Just in case
1621                         return;
1622
1623                 if(do_interpolate)
1624                 {
1625                         if(!m_prop.physical)
1626                                 pos_translator.update(m_position, is_end_position, update_interval);
1627                 } else {
1628                         pos_translator.init(m_position);
1629                 }
1630                 updateNodePos();
1631         } else if (cmd == GENERIC_CMD_SET_TEXTURE_MOD) {
1632                 std::string mod = deSerializeString(is);
1633
1634                 // immediatly reset a engine issued texture modifier if a mod sends a different one
1635                 if (m_reset_textures_timer > 0) {
1636                         m_reset_textures_timer = -1;
1637                         updateTextures(m_previous_texture_modifier);
1638                 }
1639                 updateTextures(mod);
1640         } else if (cmd == GENERIC_CMD_SET_SPRITE) {
1641                 v2s16 p = readV2S16(is);
1642                 int num_frames = readU16(is);
1643                 float framelength = readF1000(is);
1644                 bool select_horiz_by_yawpitch = readU8(is);
1645
1646                 m_tx_basepos = p;
1647                 m_anim_num_frames = num_frames;
1648                 m_anim_framelength = framelength;
1649                 m_tx_select_horiz_by_yawpitch = select_horiz_by_yawpitch;
1650
1651                 updateTexturePos();
1652         } else if (cmd == GENERIC_CMD_SET_PHYSICS_OVERRIDE) {
1653                 float override_speed = readF1000(is);
1654                 float override_jump = readF1000(is);
1655                 float override_gravity = readF1000(is);
1656                 // these are sent inverted so we get true when the server sends nothing
1657                 bool sneak = !readU8(is);
1658                 bool sneak_glitch = !readU8(is);
1659                 bool new_move = !readU8(is);
1660
1661
1662                 if(m_is_local_player)
1663                 {
1664                         LocalPlayer *player = m_env->getLocalPlayer();
1665                         player->physics_override_speed = override_speed;
1666                         player->physics_override_jump = override_jump;
1667                         player->physics_override_gravity = override_gravity;
1668                         player->physics_override_sneak = sneak;
1669                         player->physics_override_sneak_glitch = sneak_glitch;
1670                         player->physics_override_new_move = new_move;
1671                 }
1672         } else if (cmd == GENERIC_CMD_SET_ANIMATION) {
1673                 // TODO: change frames send as v2s32 value
1674                 v2f range = readV2F1000(is);
1675                 if (!m_is_local_player) {
1676                         m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1677                         m_animation_speed = readF1000(is);
1678                         m_animation_blend = readF1000(is);
1679                         // these are sent inverted so we get true when the server sends nothing
1680                         m_animation_loop = !readU8(is);
1681                         updateAnimation();
1682                 } else {
1683                         LocalPlayer *player = m_env->getLocalPlayer();
1684                         if(player->last_animation == NO_ANIM)
1685                         {
1686                                 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1687                                 m_animation_speed = readF1000(is);
1688                                 m_animation_blend = readF1000(is);
1689                                 // these are sent inverted so we get true when the server sends nothing
1690                                 m_animation_loop = !readU8(is);
1691                         }
1692                         // update animation only if local animations present
1693                         // and received animation is unknown (except idle animation)
1694                         bool is_known = false;
1695                         for (int i = 1;i<4;i++)
1696                         {
1697                                 if(m_animation_range.Y == player->local_animations[i].Y)
1698                                         is_known = true;
1699                         }
1700                         if(!is_known ||
1701                                         (player->local_animations[1].Y + player->local_animations[2].Y < 1))
1702                         {
1703                                         updateAnimation();
1704                         }
1705                 }
1706         } else if (cmd == GENERIC_CMD_SET_BONE_POSITION) {
1707                 std::string bone = deSerializeString(is);
1708                 v3f position = readV3F1000(is);
1709                 v3f rotation = readV3F1000(is);
1710                 m_bone_position[bone] = core::vector2d<v3f>(position, rotation);
1711
1712                 updateBonePosition();
1713         } else if (cmd == GENERIC_CMD_ATTACH_TO) {
1714                 u16 parentID = readS16(is);
1715                 u16 oldparent = m_env->attachement_parent_ids[getId()];
1716                 if (oldparent) {
1717                         m_children.erase(std::remove(m_children.begin(), m_children.end(),
1718                                 getId()), m_children.end());
1719                 }
1720                 m_env->attachement_parent_ids[getId()] = parentID;
1721                 GenericCAO *parentobj = m_env->getGenericCAO(parentID);
1722
1723                 if (parentobj) {
1724                         parentobj->m_children.push_back(getId());
1725                 }
1726
1727                 m_attachment_bone = deSerializeString(is);
1728                 m_attachment_position = readV3F1000(is);
1729                 m_attachment_rotation = readV3F1000(is);
1730
1731                 // localplayer itself can't be attached to localplayer
1732                 if (!m_is_local_player) {
1733                         m_attached_to_local = getParent() != NULL && getParent()->isLocalPlayer();
1734                         // Objects attached to the local player should be hidden by default
1735                         m_is_visible = !m_attached_to_local;
1736                 }
1737
1738                 updateAttachments();
1739         } else if (cmd == GENERIC_CMD_PUNCHED) {
1740                 /*s16 damage =*/ readS16(is);
1741                 s16 result_hp = readS16(is);
1742
1743                 // Use this instead of the send damage to not interfere with prediction
1744                 s16 damage = m_hp - result_hp;
1745
1746                 m_hp = result_hp;
1747
1748                 if (damage > 0)
1749                 {
1750                         if (m_hp <= 0)
1751                         {
1752                                 // TODO: Execute defined fast response
1753                                 // As there is no definition, make a smoke puff
1754                                 ClientSimpleObject *simple = createSmokePuff(
1755                                                 m_smgr, m_env, m_position,
1756                                                 m_prop.visual_size * BS);
1757                                 m_env->addSimpleObject(simple);
1758                         } else {
1759                                 // TODO: Execute defined fast response
1760                                 // Flashing shall suffice as there is no definition
1761                                 m_reset_textures_timer = 0.05;
1762                                 if(damage >= 2)
1763                                         m_reset_textures_timer += 0.05 * damage;
1764                                 updateTextures(m_current_texture_modifier + "^[brighten");
1765                         }
1766                 }
1767         } else if (cmd == GENERIC_CMD_UPDATE_ARMOR_GROUPS) {
1768                 m_armor_groups.clear();
1769                 int armor_groups_size = readU16(is);
1770                 for(int i=0; i<armor_groups_size; i++)
1771                 {
1772                         std::string name = deSerializeString(is);
1773                         int rating = readS16(is);
1774                         m_armor_groups[name] = rating;
1775                 }
1776         } else if (cmd == GENERIC_CMD_UPDATE_NAMETAG_ATTRIBUTES) {
1777                 // Deprecated, for backwards compatibility only.
1778                 readU8(is); // version
1779                 m_prop.nametag_color = readARGB8(is);
1780                 if (m_nametag != NULL) {
1781                         m_nametag->nametag_color = m_prop.nametag_color;
1782                 }
1783         } else if (cmd == GENERIC_CMD_SPAWN_INFANT) {
1784                 u16 child_id = readU16(is);
1785                 u8 type = readU8(is);
1786
1787                 if (GenericCAO *childobj = m_env->getGenericCAO(child_id)) {
1788                         childobj->processInitData(deSerializeLongString(is));
1789                 } else {
1790                         m_env->addActiveObject(child_id, type, deSerializeLongString(is));
1791                 }
1792         } else {
1793                 warningstream << FUNCTION_NAME
1794                         << ": unknown command or outdated client \""
1795                         << +cmd << "\"" << std::endl;
1796         }
1797 }
1798
1799 /* \pre punchitem != NULL
1800  */
1801 bool GenericCAO::directReportPunch(v3f dir, const ItemStack *punchitem,
1802                 float time_from_last_punch)
1803 {
1804         assert(punchitem);      // pre-condition
1805         const ToolCapabilities *toolcap =
1806                         &punchitem->getToolCapabilities(m_client->idef());
1807         PunchDamageResult result = getPunchDamage(
1808                         m_armor_groups,
1809                         toolcap,
1810                         punchitem,
1811                         time_from_last_punch);
1812
1813         if(result.did_punch && result.damage != 0)
1814         {
1815                 if(result.damage < m_hp)
1816                 {
1817                         m_hp -= result.damage;
1818                 } else {
1819                         m_hp = 0;
1820                         // TODO: Execute defined fast response
1821                         // As there is no definition, make a smoke puff
1822                         ClientSimpleObject *simple = createSmokePuff(
1823                                         m_smgr, m_env, m_position,
1824                                         m_prop.visual_size * BS);
1825                         m_env->addSimpleObject(simple);
1826                 }
1827                 // TODO: Execute defined fast response
1828                 // Flashing shall suffice as there is no definition
1829                 m_reset_textures_timer = 0.05;
1830                 if(result.damage >= 2)
1831                         m_reset_textures_timer += 0.05 * result.damage;
1832                 updateTextures(m_current_texture_modifier + "^[brighten");
1833         }
1834
1835         return false;
1836 }
1837
1838 std::string GenericCAO::debugInfoText()
1839 {
1840         std::ostringstream os(std::ios::binary);
1841         os<<"GenericCAO hp="<<m_hp<<"\n";
1842         os<<"armor={";
1843         for(ItemGroupList::const_iterator i = m_armor_groups.begin();
1844                         i != m_armor_groups.end(); ++i)
1845         {
1846                 os<<i->first<<"="<<i->second<<", ";
1847         }
1848         os<<"}";
1849         return os.str();
1850 }
1851
1852 // Prototype
1853 GenericCAO proto_GenericCAO(NULL, NULL);