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