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