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