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