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