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