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