]> git.lizzy.rs Git - dragonfireclient.git/blob - src/client/content_cao.cpp
ContentCAO: Fix segfault when minimap is disabled
[dragonfireclient.git] / src / client / 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 "content_cao.h"
21 #include <IBillboardSceneNode.h>
22 #include <ICameraSceneNode.h>
23 #include <ITextSceneNode.h>
24 #include <IMeshManipulator.h>
25 #include <IAnimatedMeshSceneNode.h>
26 #include "client/client.h"
27 #include "client/renderingengine.h"
28 #include "client/sound.h"
29 #include "client/tile.h"
30 #include "util/basic_macros.h"
31 #include "util/numeric.h" // For IntervalLimiter & setPitchYawRoll
32 #include "util/serialize.h"
33 #include "camera.h" // CameraModes
34 #include "collision.h"
35 #include "content_cso.h"
36 #include "environment.h"
37 #include "itemdef.h"
38 #include "localplayer.h"
39 #include "map.h"
40 #include "mesh.h"
41 #include "nodedef.h"
42 #include "serialization.h" // For decompressZlib
43 #include "settings.h"
44 #include "sound.h"
45 #include "tool.h"
46 #include "wieldmesh.h"
47 #include <algorithm>
48 #include <cmath>
49 #include "client/shader.h"
50 #include "client/minimap.h"
51
52 class Settings;
53 struct ToolCapabilities;
54
55 std::unordered_map<u16, ClientActiveObject::Factory> ClientActiveObject::m_types;
56
57 template<typename T>
58 void SmoothTranslator<T>::init(T current)
59 {
60         val_old = current;
61         val_current = current;
62         val_target = current;
63         anim_time = 0;
64         anim_time_counter = 0;
65         aim_is_end = true;
66 }
67
68 template<typename T>
69 void SmoothTranslator<T>::update(T new_target, bool is_end_position, float update_interval)
70 {
71         aim_is_end = is_end_position;
72         val_old = val_current;
73         val_target = new_target;
74         if (update_interval > 0) {
75                 anim_time = update_interval;
76         } else {
77                 if (anim_time < 0.001 || anim_time > 1.0)
78                         anim_time = anim_time_counter;
79                 else
80                         anim_time = anim_time * 0.9 + anim_time_counter * 0.1;
81         }
82         anim_time_counter = 0;
83 }
84
85 template<typename T>
86 void SmoothTranslator<T>::translate(f32 dtime)
87 {
88         anim_time_counter = anim_time_counter + dtime;
89         T val_diff = val_target - val_old;
90         f32 moveratio = 1.0;
91         if (anim_time > 0.001)
92                 moveratio = anim_time_counter / anim_time;
93         f32 move_end = aim_is_end ? 1.0 : 1.5;
94
95         // Move a bit less than should, to avoid oscillation
96         moveratio = std::min(moveratio * 0.8f, move_end);
97         val_current = val_old + val_diff * moveratio;
98 }
99
100 void SmoothTranslatorWrapped::translate(f32 dtime)
101 {
102         anim_time_counter = anim_time_counter + dtime;
103         f32 val_diff = std::abs(val_target - val_old);
104         if (val_diff > 180.f)
105                 val_diff = 360.f - val_diff;
106
107         f32 moveratio = 1.0;
108         if (anim_time > 0.001)
109                 moveratio = anim_time_counter / anim_time;
110         f32 move_end = aim_is_end ? 1.0 : 1.5;
111
112         // Move a bit less than should, to avoid oscillation
113         moveratio = std::min(moveratio * 0.8f, move_end);
114         wrappedApproachShortest(val_current, val_target,
115                 val_diff * moveratio, 360.f);
116 }
117
118 void SmoothTranslatorWrappedv3f::translate(f32 dtime)
119 {
120         anim_time_counter = anim_time_counter + dtime;
121
122         v3f val_diff_v3f;
123         val_diff_v3f.X = std::abs(val_target.X - val_old.X);
124         val_diff_v3f.Y = std::abs(val_target.Y - val_old.Y);
125         val_diff_v3f.Z = std::abs(val_target.Z - val_old.Z);
126
127         if (val_diff_v3f.X > 180.f)
128                 val_diff_v3f.X = 360.f - val_diff_v3f.X;
129
130         if (val_diff_v3f.Y > 180.f)
131                 val_diff_v3f.Y = 360.f - val_diff_v3f.Y;
132
133         if (val_diff_v3f.Z > 180.f)
134                 val_diff_v3f.Z = 360.f - val_diff_v3f.Z;
135
136         f32 moveratio = 1.0;
137         if (anim_time > 0.001)
138                 moveratio = anim_time_counter / anim_time;
139         f32 move_end = aim_is_end ? 1.0 : 1.5;
140
141         // Move a bit less than should, to avoid oscillation
142         moveratio = std::min(moveratio * 0.8f, move_end);
143         wrappedApproachShortest(val_current.X, val_target.X,
144                 val_diff_v3f.X * moveratio, 360.f);
145
146         wrappedApproachShortest(val_current.Y, val_target.Y,
147                 val_diff_v3f.Y * moveratio, 360.f);
148
149         wrappedApproachShortest(val_current.Z, val_target.Z,
150                 val_diff_v3f.Z * moveratio, 360.f);
151 }
152
153 /*
154         Other stuff
155 */
156
157 static void setBillboardTextureMatrix(scene::IBillboardSceneNode *bill,
158                 float txs, float tys, int col, int row)
159 {
160         video::SMaterial& material = bill->getMaterial(0);
161         core::matrix4& matrix = material.getTextureMatrix(0);
162         matrix.setTextureTranslate(txs*col, tys*row);
163         matrix.setTextureScale(txs, tys);
164 }
165
166 // Evaluate transform chain recursively; irrlicht does not do this for us
167 static void updatePositionRecursive(scene::ISceneNode *node)
168 {
169         scene::ISceneNode *parent = node->getParent();
170         if (parent)
171                 updatePositionRecursive(parent);
172         node->updateAbsolutePosition();
173 }
174
175 /*
176         TestCAO
177 */
178
179 class TestCAO : public ClientActiveObject
180 {
181 public:
182         TestCAO(Client *client, ClientEnvironment *env);
183         virtual ~TestCAO() = default;
184
185         ActiveObjectType getType() const
186         {
187                 return ACTIVEOBJECT_TYPE_TEST;
188         }
189
190         static ClientActiveObject* create(Client *client, ClientEnvironment *env);
191
192         void addToScene(ITextureSource *tsrc);
193         void removeFromScene(bool permanent);
194         void updateLight(u32 day_night_ratio);
195         void updateNodePos();
196
197         void step(float dtime, ClientEnvironment *env);
198
199         void processMessage(const std::string &data);
200
201         bool getCollisionBox(aabb3f *toset) const { return false; }
202 private:
203         scene::IMeshSceneNode *m_node;
204         v3f m_position;
205 };
206
207 // Prototype
208 TestCAO proto_TestCAO(NULL, NULL);
209
210 TestCAO::TestCAO(Client *client, ClientEnvironment *env):
211         ClientActiveObject(0, client, env),
212         m_node(NULL),
213         m_position(v3f(0,10*BS,0))
214 {
215         ClientActiveObject::registerType(getType(), create);
216 }
217
218 ClientActiveObject* TestCAO::create(Client *client, ClientEnvironment *env)
219 {
220         return new TestCAO(client, env);
221 }
222
223 void TestCAO::addToScene(ITextureSource *tsrc)
224 {
225         if(m_node != NULL)
226                 return;
227
228         //video::IVideoDriver* driver = smgr->getVideoDriver();
229
230         scene::SMesh *mesh = new scene::SMesh();
231         scene::IMeshBuffer *buf = new scene::SMeshBuffer();
232         video::SColor c(255,255,255,255);
233         video::S3DVertex vertices[4] =
234         {
235                 video::S3DVertex(-BS/2,-BS/4,0, 0,0,0, c, 0,1),
236                 video::S3DVertex(BS/2,-BS/4,0, 0,0,0, c, 1,1),
237                 video::S3DVertex(BS/2,BS/4,0, 0,0,0, c, 1,0),
238                 video::S3DVertex(-BS/2,BS/4,0, 0,0,0, c, 0,0),
239         };
240         u16 indices[] = {0,1,2,2,3,0};
241         buf->append(vertices, 4, indices, 6);
242         // Set material
243         buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
244         buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
245         buf->getMaterial().setTexture(0, tsrc->getTextureForMesh("rat.png"));
246         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
247         buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
248         buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
249         // Add to mesh
250         mesh->addMeshBuffer(buf);
251         buf->drop();
252         m_node = RenderingEngine::get_scene_manager()->addMeshSceneNode(mesh, NULL);
253         mesh->drop();
254         updateNodePos();
255 }
256
257 void TestCAO::removeFromScene(bool permanent)
258 {
259         if (!m_node)
260                 return;
261
262         m_node->remove();
263         m_node = NULL;
264 }
265
266 void TestCAO::updateLight(u32 day_night_ratio)
267 {
268 }
269
270 void TestCAO::updateNodePos()
271 {
272         if (!m_node)
273                 return;
274
275         m_node->setPosition(m_position);
276         //m_node->setRotation(v3f(0, 45, 0));
277 }
278
279 void TestCAO::step(float dtime, ClientEnvironment *env)
280 {
281         if(m_node)
282         {
283                 v3f rot = m_node->getRotation();
284                 //infostream<<"dtime="<<dtime<<", rot.Y="<<rot.Y<<std::endl;
285                 rot.Y += dtime * 180;
286                 m_node->setRotation(rot);
287         }
288 }
289
290 void TestCAO::processMessage(const std::string &data)
291 {
292         infostream<<"TestCAO: Got data: "<<data<<std::endl;
293         std::istringstream is(data, std::ios::binary);
294         u16 cmd;
295         is>>cmd;
296         if(cmd == 0)
297         {
298                 v3f newpos;
299                 is>>newpos.X;
300                 is>>newpos.Y;
301                 is>>newpos.Z;
302                 m_position = newpos;
303                 updateNodePos();
304         }
305 }
306
307 /*
308         GenericCAO
309 */
310
311 #include "clientobject.h"
312
313 GenericCAO::GenericCAO(Client *client, ClientEnvironment *env):
314                 ClientActiveObject(0, client, env)
315 {
316         if (client == NULL) {
317                 ClientActiveObject::registerType(getType(), create);
318         } else {
319                 m_client = client;
320         }
321 }
322
323 bool GenericCAO::getCollisionBox(aabb3f *toset) const
324 {
325         if (m_prop.physical)
326         {
327                 //update collision box
328                 toset->MinEdge = m_prop.collisionbox.MinEdge * BS;
329                 toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS;
330
331                 toset->MinEdge += m_position;
332                 toset->MaxEdge += m_position;
333
334                 return true;
335         }
336
337         return false;
338 }
339
340 bool GenericCAO::collideWithObjects() const
341 {
342         return m_prop.collideWithObjects;
343 }
344
345 void GenericCAO::initialize(const std::string &data)
346 {
347         infostream<<"GenericCAO: Got init data"<<std::endl;
348         processInitData(data);
349
350         if (m_is_player) {
351                 // Check if it's the current player
352                 LocalPlayer *player = m_env->getLocalPlayer();
353                 if (player && strcmp(player->getName(), m_name.c_str()) == 0) {
354                         m_is_local_player = true;
355                         m_is_visible = false;
356                         player->setCAO(this);
357
358                         m_prop.show_on_minimap = false;
359                 }
360         }
361
362         m_enable_shaders = g_settings->getBool("enable_shaders");
363 }
364
365 void GenericCAO::processInitData(const std::string &data)
366 {
367         std::istringstream is(data, std::ios::binary);
368         const u8 version = readU8(is);
369
370         if (version < 1) {
371                 errorstream << "GenericCAO: Unsupported init data version"
372                                 << std::endl;
373                 return;
374         }
375
376         // PROTOCOL_VERSION >= 37
377         m_name = deSerializeString16(is);
378         m_is_player = readU8(is);
379         m_id = readU16(is);
380         m_position = readV3F32(is);
381         m_rotation = readV3F32(is);
382         m_hp = readU16(is);
383
384         const u8 num_messages = readU8(is);
385
386         for (int i = 0; i < num_messages; i++) {
387                 std::string message = deSerializeString32(is);
388                 processMessage(message);
389         }
390
391         m_rotation = wrapDegrees_0_360_v3f(m_rotation);
392         pos_translator.init(m_position);
393         rot_translator.init(m_rotation);
394         updateNodePos();
395 }
396
397 GenericCAO::~GenericCAO()
398 {
399         removeFromScene(true);
400 }
401
402 bool GenericCAO::getSelectionBox(aabb3f *toset) const
403 {
404         if (!m_prop.is_visible || !m_is_visible || m_is_local_player
405                         || !m_prop.pointable) {
406                 return false;
407         }
408         *toset = m_selection_box;
409         return true;
410 }
411
412 const v3f GenericCAO::getPosition() const
413 {
414         if (!getParent())
415                 return pos_translator.val_current;
416
417         // Calculate real position in world based on MatrixNode
418         if (m_matrixnode) {
419                 v3s16 camera_offset = m_env->getCameraOffset();
420                 return m_matrixnode->getAbsolutePosition() +
421                                 intToFloat(camera_offset, BS);
422         }
423
424         return m_position;
425 }
426
427 const bool GenericCAO::isImmortal()
428 {
429         return itemgroup_get(getGroups(), "immortal");
430 }
431
432 scene::ISceneNode *GenericCAO::getSceneNode() const
433 {
434         if (m_meshnode) {
435                 return m_meshnode;
436         }
437
438         if (m_animated_meshnode) {
439                 return m_animated_meshnode;
440         }
441
442         if (m_wield_meshnode) {
443                 return m_wield_meshnode;
444         }
445
446         if (m_spritenode) {
447                 return m_spritenode;
448         }
449         return NULL;
450 }
451
452 scene::IAnimatedMeshSceneNode *GenericCAO::getAnimatedMeshSceneNode() const
453 {
454         return m_animated_meshnode;
455 }
456
457 void GenericCAO::setChildrenVisible(bool toset)
458 {
459         for (u16 cao_id : m_attachment_child_ids) {
460                 GenericCAO *obj = m_env->getGenericCAO(cao_id);
461                 if (obj) {
462                         // Check if the entity is forced to appear in first person.
463                         obj->setVisible(obj->isForcedVisible() ? true : toset);
464                 }
465         }
466 }
467
468 void GenericCAO::setAttachment(int parent_id, const std::string &bone, v3f position, v3f rotation)
469 {
470         int old_parent = m_attachment_parent_id;
471         m_attachment_parent_id = parent_id;
472         m_attachment_bone = bone;
473         m_attachment_position = position;
474         m_attachment_rotation = rotation;
475
476         ClientActiveObject *parent = m_env->getActiveObject(parent_id);
477
478         if (parent_id != old_parent) {
479                 if (auto *o = m_env->getActiveObject(old_parent))
480                         o->removeAttachmentChild(m_id);
481                 if (parent)
482                         parent->addAttachmentChild(m_id);
483         }
484         updateAttachments();
485 }
486
487 void GenericCAO::getAttachment(int *parent_id, std::string *bone, v3f *position,
488         v3f *rotation) const
489 {
490         *parent_id = m_attachment_parent_id;
491         *bone = m_attachment_bone;
492         *position = m_attachment_position;
493         *rotation = m_attachment_rotation;
494 }
495
496 void GenericCAO::clearChildAttachments()
497 {
498         // Cannot use for-loop here: setAttachment() modifies 'm_attachment_child_ids'!
499         while (!m_attachment_child_ids.empty()) {
500                 int child_id = *m_attachment_child_ids.begin();
501
502                 if (ClientActiveObject *child = m_env->getActiveObject(child_id))
503                         child->setAttachment(0, "", v3f(), v3f(), false);
504
505                 removeAttachmentChild(child_id);
506         }
507 }
508
509 void GenericCAO::clearParentAttachment()
510 {
511         if (m_attachment_parent_id)
512                 setAttachment(0, "", m_attachment_position, m_attachment_rotation);
513         else
514                 setAttachment(0, "", v3f(), v3f());
515 }
516
517 void GenericCAO::addAttachmentChild(int child_id)
518 {
519         m_attachment_child_ids.insert(child_id);
520 }
521
522 void GenericCAO::removeAttachmentChild(int child_id)
523 {
524         m_attachment_child_ids.erase(child_id);
525 }
526
527 ClientActiveObject* GenericCAO::getParent() const
528 {
529         return m_attachment_parent_id ? m_env->getActiveObject(m_attachment_parent_id) :
530                         nullptr;
531 }
532
533 void GenericCAO::removeFromScene(bool permanent)
534 {
535         // Should be true when removing the object permanently
536         // and false when refreshing (eg: updating visuals)
537         if (m_env && permanent) {
538                 // The client does not know whether this object does re-appear to
539                 // a later time, thus do not clear child attachments.
540
541                 clearParentAttachment();
542         }
543
544         if (m_meshnode) {
545                 m_meshnode->remove();
546                 m_meshnode->drop();
547                 m_meshnode = nullptr;
548         } else if (m_animated_meshnode) {
549                 m_animated_meshnode->remove();
550                 m_animated_meshnode->drop();
551                 m_animated_meshnode = nullptr;
552         } else if (m_wield_meshnode) {
553                 m_wield_meshnode->remove();
554                 m_wield_meshnode->drop();
555                 m_wield_meshnode = nullptr;
556         } else if (m_spritenode) {
557                 m_spritenode->remove();
558                 m_spritenode->drop();
559                 m_spritenode = nullptr;
560         }
561
562         if (m_matrixnode) {
563                 m_matrixnode->remove();
564                 m_matrixnode->drop();
565                 m_matrixnode = nullptr;
566         }
567
568         if (m_nametag) {
569                 m_client->getCamera()->removeNametag(m_nametag);
570                 m_nametag = nullptr;
571         }
572
573         if (m_marker && m_client->getMinimap())
574                 m_client->getMinimap()->removeMarker(&m_marker);
575 }
576
577 void GenericCAO::addToScene(ITextureSource *tsrc)
578 {
579         m_smgr = RenderingEngine::get_scene_manager();
580
581         if (getSceneNode() != NULL) {
582                 return;
583         }
584
585         m_visuals_expired = false;
586
587         if (!m_prop.is_visible)
588                 return;
589
590         infostream << "GenericCAO::addToScene(): " << m_prop.visual << std::endl;
591
592         if (m_enable_shaders) {
593                 IShaderSource *shader_source = m_client->getShaderSource();
594                 MaterialType material_type;
595
596                 if (m_prop.shaded && m_prop.glow == 0)
597                         material_type = (m_prop.use_texture_alpha) ?
598                                 TILE_MATERIAL_ALPHA : TILE_MATERIAL_BASIC;
599                 else
600                         material_type = (m_prop.use_texture_alpha) ?
601                                 TILE_MATERIAL_PLAIN_ALPHA : TILE_MATERIAL_PLAIN;
602
603                 u32 shader_id = shader_source->getShader("object_shader", material_type, NDT_NORMAL);
604                 m_material_type = shader_source->getShaderInfo(shader_id).material;
605         } else {
606                 m_material_type = (m_prop.use_texture_alpha) ?
607                         video::EMT_TRANSPARENT_ALPHA_CHANNEL : video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
608         }
609
610         auto grabMatrixNode = [this] {
611                 m_matrixnode = RenderingEngine::get_scene_manager()->
612                                 addDummyTransformationSceneNode();
613                 m_matrixnode->grab();
614         };
615
616         auto setSceneNodeMaterial = [this] (scene::ISceneNode *node) {
617                 node->setMaterialFlag(video::EMF_LIGHTING, false);
618                 node->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
619                 node->setMaterialFlag(video::EMF_FOG_ENABLE, true);
620                 node->setMaterialType(m_material_type);
621
622                 if (m_enable_shaders) {
623                         node->setMaterialFlag(video::EMF_GOURAUD_SHADING, false);
624                         node->setMaterialFlag(video::EMF_NORMALIZE_NORMALS, true);
625                 }
626         };
627
628         if (m_prop.visual == "sprite") {
629                 grabMatrixNode();
630                 m_spritenode = RenderingEngine::get_scene_manager()->addBillboardSceneNode(
631                                 m_matrixnode, v2f(1, 1), v3f(0,0,0), -1);
632                 m_spritenode->grab();
633                 m_spritenode->setMaterialTexture(0,
634                                 tsrc->getTextureForMesh("unknown_node.png"));
635
636                 setSceneNodeMaterial(m_spritenode);
637
638                 m_spritenode->setSize(v2f(m_prop.visual_size.X,
639                                 m_prop.visual_size.Y) * BS);
640                 {
641                         const float txs = 1.0 / 1;
642                         const float tys = 1.0 / 1;
643                         setBillboardTextureMatrix(m_spritenode,
644                                         txs, tys, 0, 0);
645                 }
646         } else if (m_prop.visual == "upright_sprite") {
647                 grabMatrixNode();
648                 scene::SMesh *mesh = new scene::SMesh();
649                 double dx = BS * m_prop.visual_size.X / 2;
650                 double dy = BS * m_prop.visual_size.Y / 2;
651                 video::SColor c(0xFFFFFFFF);
652
653                 { // Front
654                         scene::IMeshBuffer *buf = new scene::SMeshBuffer();
655                         video::S3DVertex vertices[4] = {
656                                 video::S3DVertex(-dx, -dy, 0, 0,0,1, c, 1,1),
657                                 video::S3DVertex( dx, -dy, 0, 0,0,1, c, 0,1),
658                                 video::S3DVertex( dx,  dy, 0, 0,0,1, c, 0,0),
659                                 video::S3DVertex(-dx,  dy, 0, 0,0,1, c, 1,0),
660                         };
661                         if (m_is_player) {
662                                 // Move minimal Y position to 0 (feet position)
663                                 for (video::S3DVertex &vertex : vertices)
664                                         vertex.Pos.Y += dy;
665                         }
666                         u16 indices[] = {0,1,2,2,3,0};
667                         buf->append(vertices, 4, indices, 6);
668                         // Set material
669                         buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
670                         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
671                         buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
672                         buf->getMaterial().MaterialType = m_material_type;
673
674                         if (m_enable_shaders) {
675                                 buf->getMaterial().EmissiveColor = c;
676                                 buf->getMaterial().setFlag(video::EMF_GOURAUD_SHADING, false);
677                                 buf->getMaterial().setFlag(video::EMF_NORMALIZE_NORMALS, true);
678                         }
679
680                         // Add to mesh
681                         mesh->addMeshBuffer(buf);
682                         buf->drop();
683                 }
684                 { // Back
685                         scene::IMeshBuffer *buf = new scene::SMeshBuffer();
686                         video::S3DVertex vertices[4] = {
687                                 video::S3DVertex( dx,-dy, 0, 0,0,-1, c, 1,1),
688                                 video::S3DVertex(-dx,-dy, 0, 0,0,-1, c, 0,1),
689                                 video::S3DVertex(-dx, dy, 0, 0,0,-1, c, 0,0),
690                                 video::S3DVertex( dx, dy, 0, 0,0,-1, c, 1,0),
691                         };
692                         if (m_is_player) {
693                                 // Move minimal Y position to 0 (feet position)
694                                 for (video::S3DVertex &vertex : vertices)
695                                         vertex.Pos.Y += dy;
696                         }
697                         u16 indices[] = {0,1,2,2,3,0};
698                         buf->append(vertices, 4, indices, 6);
699                         // Set material
700                         buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
701                         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
702                         buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
703                         buf->getMaterial().MaterialType = m_material_type;
704
705                         if (m_enable_shaders) {
706                                 buf->getMaterial().EmissiveColor = c;
707                                 buf->getMaterial().setFlag(video::EMF_GOURAUD_SHADING, false);
708                                 buf->getMaterial().setFlag(video::EMF_NORMALIZE_NORMALS, true);
709                         }
710
711                         // Add to mesh
712                         mesh->addMeshBuffer(buf);
713                         buf->drop();
714                 }
715                 m_meshnode = RenderingEngine::get_scene_manager()->
716                         addMeshSceneNode(mesh, m_matrixnode);
717                 m_meshnode->grab();
718                 mesh->drop();
719                 // Set it to use the materials of the meshbuffers directly.
720                 // This is needed for changing the texture in the future
721                 m_meshnode->setReadOnlyMaterials(true);
722         } else if (m_prop.visual == "cube") {
723                 grabMatrixNode();
724                 scene::IMesh *mesh = createCubeMesh(v3f(BS,BS,BS));
725                 m_meshnode = RenderingEngine::get_scene_manager()->
726                         addMeshSceneNode(mesh, m_matrixnode);
727                 m_meshnode->grab();
728                 mesh->drop();
729
730                 m_meshnode->setScale(m_prop.visual_size);
731                 m_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
732                         m_prop.backface_culling);
733
734                 setSceneNodeMaterial(m_meshnode);
735         } else if (m_prop.visual == "mesh") {
736                 grabMatrixNode();
737                 scene::IAnimatedMesh *mesh = m_client->getMesh(m_prop.mesh, true);
738                 if (mesh) {
739                         m_animated_meshnode = RenderingEngine::get_scene_manager()->
740                                 addAnimatedMeshSceneNode(mesh, m_matrixnode);
741                         m_animated_meshnode->grab();
742                         mesh->drop(); // The scene node took hold of it
743
744                         if (!checkMeshNormals(mesh)) {
745                                 infostream << "GenericCAO: recalculating normals for mesh "
746                                         << m_prop.mesh << std::endl;
747                                 m_smgr->getMeshManipulator()->
748                                                 recalculateNormals(mesh, true, false);
749                         }
750
751                         m_animated_meshnode->animateJoints(); // Needed for some animations
752                         m_animated_meshnode->setScale(m_prop.visual_size);
753
754                         // set vertex colors to ensure alpha is set
755                         setMeshColor(m_animated_meshnode->getMesh(), video::SColor(0xFFFFFFFF));
756
757                         setAnimatedMeshColor(m_animated_meshnode, video::SColor(0xFFFFFFFF));
758
759                         setSceneNodeMaterial(m_animated_meshnode);
760
761                         m_animated_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
762                                 m_prop.backface_culling);
763                 } else
764                         errorstream<<"GenericCAO::addToScene(): Could not load mesh "<<m_prop.mesh<<std::endl;
765         } else if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
766                 grabMatrixNode();
767                 ItemStack item;
768                 if (m_prop.wield_item.empty()) {
769                         // Old format, only textures are specified.
770                         infostream << "textures: " << m_prop.textures.size() << std::endl;
771                         if (!m_prop.textures.empty()) {
772                                 infostream << "textures[0]: " << m_prop.textures[0]
773                                         << std::endl;
774                                 IItemDefManager *idef = m_client->idef();
775                                 item = ItemStack(m_prop.textures[0], 1, 0, idef);
776                         }
777                 } else {
778                         infostream << "serialized form: " << m_prop.wield_item << std::endl;
779                         item.deSerialize(m_prop.wield_item, m_client->idef());
780                 }
781                 m_wield_meshnode = new WieldMeshSceneNode(
782                         RenderingEngine::get_scene_manager(), -1);
783                 m_wield_meshnode->setItem(item, m_client,
784                         (m_prop.visual == "wielditem"));
785
786                 m_wield_meshnode->setScale(m_prop.visual_size / 2.0f);
787                 m_wield_meshnode->setColor(video::SColor(0xFFFFFFFF));
788         } else {
789                 infostream<<"GenericCAO::addToScene(): \""<<m_prop.visual
790                                 <<"\" not supported"<<std::endl;
791         }
792
793         /* don't update while punch texture modifier is active */
794         if (m_reset_textures_timer < 0)
795                 updateTextures(m_current_texture_modifier);
796
797         scene::ISceneNode *node = getSceneNode();
798
799         if (node && m_matrixnode)
800                 node->setParent(m_matrixnode);
801
802         updateNametag();
803         updateMarker();
804         updateNodePos();
805         updateAnimation();
806         updateBonePosition();
807         updateAttachments();
808         setNodeLight(m_last_light);
809         updateMeshCulling();
810 }
811
812 void GenericCAO::updateLight(u32 day_night_ratio)
813 {
814         if (m_glow < 0)
815                 return;
816
817         u8 light_at_pos = 0;
818         bool pos_ok = false;
819
820         v3s16 pos[3];
821         u16 npos = getLightPosition(pos);
822         for (u16 i = 0; i < npos; i++) {
823                 bool this_ok;
824                 MapNode n = m_env->getMap().getNode(pos[i], &this_ok);
825                 if (this_ok) {
826                         u8 this_light = n.getLightBlend(day_night_ratio, m_client->ndef());
827                         light_at_pos = MYMAX(light_at_pos, this_light);
828                         pos_ok = true;
829                 }
830         }
831         if (!pos_ok)
832                 light_at_pos = blend_light(day_night_ratio, LIGHT_SUN, 0);
833
834         u8 light = decode_light(light_at_pos + m_glow);
835         if (light != m_last_light) {
836                 m_last_light = light;
837                 setNodeLight(light);
838         }
839 }
840
841 void GenericCAO::setNodeLight(u8 light)
842 {
843         video::SColor color(255, light, light, light);
844
845         if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
846                 if (m_wield_meshnode)
847                         m_wield_meshnode->setNodeLightColor(color);
848                 return;
849         }
850
851         if (m_enable_shaders) {
852                 if (m_prop.visual == "upright_sprite") {
853                         if (!m_meshnode)
854                                 return;
855
856                         scene::IMesh *mesh = m_meshnode->getMesh();
857                         for (u32 i = 0; i < mesh->getMeshBufferCount(); ++i) {
858                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
859                                 buf->getMaterial().EmissiveColor = color;
860                         }
861                 } else {
862                         scene::ISceneNode *node = getSceneNode();
863                         if (!node)
864                                 return;
865
866                         for (u32 i = 0; i < node->getMaterialCount(); ++i) {
867                                 video::SMaterial &material = node->getMaterial(i);
868                                 material.EmissiveColor = color;
869                         }
870                 }
871         } else {
872                 if (m_meshnode) {
873                         setMeshColor(m_meshnode->getMesh(), color);
874                 } else if (m_animated_meshnode) {
875                         setAnimatedMeshColor(m_animated_meshnode, color);
876                 } else if (m_spritenode) {
877                         m_spritenode->setColor(color);
878                 }
879         }
880 }
881
882 u16 GenericCAO::getLightPosition(v3s16 *pos)
883 {
884         const auto &box = m_prop.collisionbox;
885         pos[0] = floatToInt(m_position + box.MinEdge * BS, BS);
886         pos[1] = floatToInt(m_position + box.MaxEdge * BS, BS);
887
888         // Skip center pos if it falls into the same node as Min or MaxEdge
889         if ((box.MaxEdge - box.MinEdge).getLengthSQ() < 3.0f)
890                 return 2;
891         pos[2] = floatToInt(m_position + box.getCenter() * BS, BS);
892         return 3;
893 }
894
895 void GenericCAO::updateMarker()
896 {
897         if (!m_client->getMinimap())
898                 return;
899
900         if (!m_prop.show_on_minimap) {
901                 if (m_marker)
902                         m_client->getMinimap()->removeMarker(&m_marker);
903                 return;
904         }
905
906         if (m_marker)
907                 return;
908
909         scene::ISceneNode *node = getSceneNode();
910         if (!node)
911                 return;
912         m_marker = m_client->getMinimap()->addMarker(node);
913 }
914
915 void GenericCAO::updateNametag()
916 {
917         if (m_is_local_player) // No nametag for local player
918                 return;
919
920         if (m_prop.nametag.empty()) {
921                 // Delete nametag
922                 if (m_nametag) {
923                         m_client->getCamera()->removeNametag(m_nametag);
924                         m_nametag = nullptr;
925                 }
926                 return;
927         }
928
929         scene::ISceneNode *node = getSceneNode();
930         if (!node)
931                 return;
932
933         v3f pos;
934         pos.Y = m_prop.selectionbox.MaxEdge.Y + 0.3f;
935         if (!m_nametag) {
936                 // Add nametag
937                 m_nametag = m_client->getCamera()->addNametag(node,
938                         m_prop.nametag, m_prop.nametag_color, pos);
939         } else {
940                 // Update nametag
941                 m_nametag->nametag_text = m_prop.nametag;
942                 m_nametag->nametag_color = m_prop.nametag_color;
943                 m_nametag->nametag_pos = pos;
944         }
945 }
946
947 void GenericCAO::updateNodePos()
948 {
949         if (getParent() != NULL)
950                 return;
951
952         scene::ISceneNode *node = getSceneNode();
953
954         if (node) {
955                 v3s16 camera_offset = m_env->getCameraOffset();
956                 v3f pos = pos_translator.val_current -
957                                 intToFloat(camera_offset, BS);
958                 getPosRotMatrix().setTranslation(pos);
959                 if (node != m_spritenode) { // rotate if not a sprite
960                         v3f rot = m_is_local_player ? -m_rotation : -rot_translator.val_current;
961                         setPitchYawRoll(getPosRotMatrix(), rot);
962                 }
963         }
964 }
965
966 void GenericCAO::step(float dtime, ClientEnvironment *env)
967 {
968         // Handle model animations and update positions instantly to prevent lags
969         if (m_is_local_player) {
970                 LocalPlayer *player = m_env->getLocalPlayer();
971                 m_position = player->getPosition();
972                 pos_translator.val_current = m_position;
973                 m_rotation.Y = wrapDegrees_0_360(player->getYaw());
974                 rot_translator.val_current = m_rotation;
975
976                 if (m_is_visible) {
977                         int old_anim = player->last_animation;
978                         float old_anim_speed = player->last_animation_speed;
979                         m_velocity = v3f(0,0,0);
980                         m_acceleration = v3f(0,0,0);
981                         const PlayerControl &controls = player->getPlayerControl();
982
983                         bool walking = false;
984                         if (controls.up || controls.down || controls.left || controls.right ||
985                                         controls.forw_move_joystick_axis != 0.f ||
986                                         controls.sidew_move_joystick_axis != 0.f)
987                                 walking = true;
988
989                         f32 new_speed = player->local_animation_speed;
990                         v2s32 new_anim = v2s32(0,0);
991                         bool allow_update = false;
992
993                         // increase speed if using fast or flying fast
994                         if((g_settings->getBool("fast_move") &&
995                                         m_client->checkLocalPrivilege("fast")) &&
996                                         (controls.aux1 ||
997                                         (!player->touching_ground &&
998                                         g_settings->getBool("free_move") &&
999                                         m_client->checkLocalPrivilege("fly"))))
1000                                         new_speed *= 1.5;
1001                         // slowdown speed if sneeking
1002                         if (controls.sneak && walking)
1003                                 new_speed /= 2;
1004
1005                         if (walking && (controls.dig || controls.place)) {
1006                                 new_anim = player->local_animations[3];
1007                                 player->last_animation = WD_ANIM;
1008                         } else if (walking) {
1009                                 new_anim = player->local_animations[1];
1010                                 player->last_animation = WALK_ANIM;
1011                         } else if (controls.dig || controls.place) {
1012                                 new_anim = player->local_animations[2];
1013                                 player->last_animation = DIG_ANIM;
1014                         }
1015
1016                         // Apply animations if input detected and not attached
1017                         // or set idle animation
1018                         if ((new_anim.X + new_anim.Y) > 0 && !getParent()) {
1019                                 allow_update = true;
1020                                 m_animation_range = new_anim;
1021                                 m_animation_speed = new_speed;
1022                                 player->last_animation_speed = m_animation_speed;
1023                         } else {
1024                                 player->last_animation = NO_ANIM;
1025
1026                                 if (old_anim != NO_ANIM) {
1027                                         m_animation_range = player->local_animations[0];
1028                                         updateAnimation();
1029                                 }
1030                         }
1031
1032                         // Update local player animations
1033                         if ((player->last_animation != old_anim ||
1034                                         m_animation_speed != old_anim_speed) &&
1035                                         player->last_animation != NO_ANIM && allow_update)
1036                                 updateAnimation();
1037
1038                 }
1039         }
1040
1041         if (m_visuals_expired && m_smgr) {
1042                 m_visuals_expired = false;
1043
1044                 // Attachments, part 1: All attached objects must be unparented first,
1045                 // or Irrlicht causes a segmentation fault
1046                 for (u16 cao_id : m_attachment_child_ids) {
1047                         ClientActiveObject *obj = m_env->getActiveObject(cao_id);
1048                         if (obj) {
1049                                 scene::ISceneNode *child_node = obj->getSceneNode();
1050                                 // The node's parent is always an IDummyTraformationSceneNode,
1051                                 // so we need to reparent that one instead.
1052                                 if (child_node)
1053                                         child_node->getParent()->setParent(m_smgr->getRootSceneNode());
1054                         }
1055                 }
1056
1057                 removeFromScene(false);
1058                 addToScene(m_client->tsrc());
1059
1060                 // Attachments, part 2: Now that the parent has been refreshed, put its attachments back
1061                 for (u16 cao_id : m_attachment_child_ids) {
1062                         ClientActiveObject *obj = m_env->getActiveObject(cao_id);
1063                         if (obj)
1064                                 obj->updateAttachments();
1065                 }
1066         }
1067
1068         // Make sure m_is_visible is always applied
1069         scene::ISceneNode *node = getSceneNode();
1070         if (node)
1071                 node->setVisible(m_is_visible);
1072
1073         if(getParent() != NULL) // Attachments should be glued to their parent by Irrlicht
1074         {
1075                 // Set these for later
1076                 m_position = getPosition();
1077                 m_velocity = v3f(0,0,0);
1078                 m_acceleration = v3f(0,0,0);
1079                 pos_translator.val_current = m_position;
1080                 pos_translator.val_target = m_position;
1081         } else {
1082                 rot_translator.translate(dtime);
1083                 v3f lastpos = pos_translator.val_current;
1084
1085                 if(m_prop.physical)
1086                 {
1087                         aabb3f box = m_prop.collisionbox;
1088                         box.MinEdge *= BS;
1089                         box.MaxEdge *= BS;
1090                         collisionMoveResult moveresult;
1091                         f32 pos_max_d = BS*0.125; // Distance per iteration
1092                         v3f p_pos = m_position;
1093                         v3f p_velocity = m_velocity;
1094                         moveresult = collisionMoveSimple(env,env->getGameDef(),
1095                                         pos_max_d, box, m_prop.stepheight, dtime,
1096                                         &p_pos, &p_velocity, m_acceleration,
1097                                         this, m_prop.collideWithObjects);
1098                         // Apply results
1099                         m_position = p_pos;
1100                         m_velocity = p_velocity;
1101
1102                         bool is_end_position = moveresult.collides;
1103                         pos_translator.update(m_position, is_end_position, dtime);
1104                 } else {
1105                         m_position += dtime * m_velocity + 0.5 * dtime * dtime * m_acceleration;
1106                         m_velocity += dtime * m_acceleration;
1107                         pos_translator.update(m_position, pos_translator.aim_is_end,
1108                                         pos_translator.anim_time);
1109                 }
1110                 pos_translator.translate(dtime);
1111                 updateNodePos();
1112
1113                 float moved = lastpos.getDistanceFrom(pos_translator.val_current);
1114                 m_step_distance_counter += moved;
1115                 if (m_step_distance_counter > 1.5f * BS) {
1116                         m_step_distance_counter = 0.0f;
1117                         if (!m_is_local_player && m_prop.makes_footstep_sound) {
1118                                 const NodeDefManager *ndef = m_client->ndef();
1119                                 v3s16 p = floatToInt(getPosition() +
1120                                         v3f(0.0f, (m_prop.collisionbox.MinEdge.Y - 0.5f) * BS, 0.0f), BS);
1121                                 MapNode n = m_env->getMap().getNode(p);
1122                                 SimpleSoundSpec spec = ndef->get(n).sound_footstep;
1123                                 // Reduce footstep gain, as non-local-player footsteps are
1124                                 // somehow louder.
1125                                 spec.gain *= 0.6f;
1126                                 m_client->sound()->playSoundAt(spec, false, getPosition());
1127                         }
1128                 }
1129         }
1130
1131         m_anim_timer += dtime;
1132         if(m_anim_timer >= m_anim_framelength)
1133         {
1134                 m_anim_timer -= m_anim_framelength;
1135                 m_anim_frame++;
1136                 if(m_anim_frame >= m_anim_num_frames)
1137                         m_anim_frame = 0;
1138         }
1139
1140         updateTexturePos();
1141
1142         if(m_reset_textures_timer >= 0)
1143         {
1144                 m_reset_textures_timer -= dtime;
1145                 if(m_reset_textures_timer <= 0) {
1146                         m_reset_textures_timer = -1;
1147                         updateTextures(m_previous_texture_modifier);
1148                 }
1149         }
1150
1151         if (!getParent() && std::fabs(m_prop.automatic_rotate) > 0.001) {
1152                 // This is the child node's rotation. It is only used for automatic_rotate.
1153                 v3f local_rot = node->getRotation();
1154                 local_rot.Y = modulo360f(local_rot.Y - dtime * core::RADTODEG *
1155                                 m_prop.automatic_rotate);
1156                 node->setRotation(local_rot);
1157         }
1158
1159         if (!getParent() && m_prop.automatic_face_movement_dir &&
1160                         (fabs(m_velocity.Z) > 0.001 || fabs(m_velocity.X) > 0.001)) {
1161                 float target_yaw = atan2(m_velocity.Z, m_velocity.X) * 180 / M_PI
1162                                 + m_prop.automatic_face_movement_dir_offset;
1163                 float max_rotation_per_sec =
1164                                 m_prop.automatic_face_movement_max_rotation_per_sec;
1165
1166                 if (max_rotation_per_sec > 0) {
1167                         wrappedApproachShortest(m_rotation.Y, target_yaw,
1168                                 dtime * max_rotation_per_sec, 360.f);
1169                 } else {
1170                         // Negative values of max_rotation_per_sec mean disabled.
1171                         m_rotation.Y = target_yaw;
1172                 }
1173
1174                 rot_translator.val_current = m_rotation;
1175                 updateNodePos();
1176         }
1177
1178         if (m_animated_meshnode) {
1179                 // Everything must be updated; the whole transform
1180                 // chain as well as the animated mesh node.
1181                 // Otherwise, bone attachments would be relative to
1182                 // a position that's one frame old.
1183                 if (m_matrixnode)
1184                         updatePositionRecursive(m_matrixnode);
1185                 m_animated_meshnode->updateAbsolutePosition();
1186                 m_animated_meshnode->animateJoints();
1187                 updateBonePosition();
1188         }
1189 }
1190
1191 void GenericCAO::updateTexturePos()
1192 {
1193         if(m_spritenode)
1194         {
1195                 scene::ICameraSceneNode* camera =
1196                                 m_spritenode->getSceneManager()->getActiveCamera();
1197                 if(!camera)
1198                         return;
1199                 v3f cam_to_entity = m_spritenode->getAbsolutePosition()
1200                                 - camera->getAbsolutePosition();
1201                 cam_to_entity.normalize();
1202
1203                 int row = m_tx_basepos.Y;
1204                 int col = m_tx_basepos.X;
1205
1206                 // Yawpitch goes rightwards
1207                 if (m_tx_select_horiz_by_yawpitch) {
1208                         if (cam_to_entity.Y > 0.75)
1209                                 col += 5;
1210                         else if (cam_to_entity.Y < -0.75)
1211                                 col += 4;
1212                         else {
1213                                 float mob_dir =
1214                                                 atan2(cam_to_entity.Z, cam_to_entity.X) / M_PI * 180.;
1215                                 float dir = mob_dir - m_rotation.Y;
1216                                 dir = wrapDegrees_180(dir);
1217                                 if (std::fabs(wrapDegrees_180(dir - 0)) <= 45.1f)
1218                                         col += 2;
1219                                 else if(std::fabs(wrapDegrees_180(dir - 90)) <= 45.1f)
1220                                         col += 3;
1221                                 else if(std::fabs(wrapDegrees_180(dir - 180)) <= 45.1f)
1222                                         col += 0;
1223                                 else if(std::fabs(wrapDegrees_180(dir + 90)) <= 45.1f)
1224                                         col += 1;
1225                                 else
1226                                         col += 4;
1227                         }
1228                 }
1229
1230                 // Animation goes downwards
1231                 row += m_anim_frame;
1232
1233                 float txs = m_tx_size.X;
1234                 float tys = m_tx_size.Y;
1235                 setBillboardTextureMatrix(m_spritenode, txs, tys, col, row);
1236         }
1237
1238         else if (m_meshnode) {
1239                 if (m_prop.visual == "upright_sprite") {
1240                         int row = m_tx_basepos.Y;
1241                         int col = m_tx_basepos.X;
1242
1243                         // Animation goes downwards
1244                         row += m_anim_frame;
1245
1246                         const auto &tx = m_tx_size;
1247                         v2f t[4] = { // cf. vertices in GenericCAO::addToScene()
1248                                 tx * v2f(col+1, row+1),
1249                                 tx * v2f(col, row+1),
1250                                 tx * v2f(col, row),
1251                                 tx * v2f(col+1, row),
1252                         };
1253                         auto mesh = m_meshnode->getMesh();
1254                         setMeshBufferTextureCoords(mesh->getMeshBuffer(0), t, 4);
1255                         setMeshBufferTextureCoords(mesh->getMeshBuffer(1), t, 4);
1256                 }
1257         }
1258 }
1259
1260 // Do not pass by reference, see header.
1261 void GenericCAO::updateTextures(std::string mod)
1262 {
1263         ITextureSource *tsrc = m_client->tsrc();
1264
1265         bool use_trilinear_filter = g_settings->getBool("trilinear_filter");
1266         bool use_bilinear_filter = g_settings->getBool("bilinear_filter");
1267         bool use_anisotropic_filter = g_settings->getBool("anisotropic_filter");
1268
1269         m_previous_texture_modifier = m_current_texture_modifier;
1270         m_current_texture_modifier = mod;
1271         m_glow = m_prop.glow;
1272
1273         if (m_spritenode) {
1274                 if (m_prop.visual == "sprite") {
1275                         std::string texturestring = "unknown_node.png";
1276                         if (!m_prop.textures.empty())
1277                                 texturestring = m_prop.textures[0];
1278                         texturestring += mod;
1279                         m_spritenode->getMaterial(0).MaterialType = m_material_type;
1280                         m_spritenode->getMaterial(0).MaterialTypeParam = 0.5f;
1281                         m_spritenode->setMaterialTexture(0,
1282                                         tsrc->getTextureForMesh(texturestring));
1283
1284                         // This allows setting per-material colors. However, until a real lighting
1285                         // system is added, the code below will have no effect. Once MineTest
1286                         // has directional lighting, it should work automatically.
1287                         if (!m_prop.colors.empty()) {
1288                                 m_spritenode->getMaterial(0).AmbientColor = m_prop.colors[0];
1289                                 m_spritenode->getMaterial(0).DiffuseColor = m_prop.colors[0];
1290                                 m_spritenode->getMaterial(0).SpecularColor = m_prop.colors[0];
1291                         }
1292
1293                         m_spritenode->getMaterial(0).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1294                         m_spritenode->getMaterial(0).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1295                         m_spritenode->getMaterial(0).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1296                 }
1297         }
1298
1299         else if (m_animated_meshnode) {
1300                 if (m_prop.visual == "mesh") {
1301                         for (u32 i = 0; i < m_prop.textures.size() &&
1302                                         i < m_animated_meshnode->getMaterialCount(); ++i) {
1303                                 std::string texturestring = m_prop.textures[i];
1304                                 if (texturestring.empty())
1305                                         continue; // Empty texture string means don't modify that material
1306                                 texturestring += mod;
1307                                 video::ITexture* texture = tsrc->getTextureForMesh(texturestring);
1308                                 if (!texture) {
1309                                         errorstream<<"GenericCAO::updateTextures(): Could not load texture "<<texturestring<<std::endl;
1310                                         continue;
1311                                 }
1312
1313                                 // Set material flags and texture
1314                                 video::SMaterial& material = m_animated_meshnode->getMaterial(i);
1315                                 material.MaterialType = m_material_type;
1316                                 material.MaterialTypeParam = 0.5f;
1317                                 material.TextureLayer[0].Texture = texture;
1318                                 material.setFlag(video::EMF_LIGHTING, true);
1319                                 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1320                                 material.setFlag(video::EMF_BACK_FACE_CULLING, m_prop.backface_culling);
1321
1322                                 // don't filter low-res textures, makes them look blurry
1323                                 // player models have a res of 64
1324                                 const core::dimension2d<u32> &size = texture->getOriginalSize();
1325                                 const u32 res = std::min(size.Height, size.Width);
1326                                 use_trilinear_filter &= res > 64;
1327                                 use_bilinear_filter &= res > 64;
1328
1329                                 m_animated_meshnode->getMaterial(i)
1330                                                 .setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1331                                 m_animated_meshnode->getMaterial(i)
1332                                                 .setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1333                                 m_animated_meshnode->getMaterial(i)
1334                                                 .setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1335                         }
1336                         for (u32 i = 0; i < m_prop.colors.size() &&
1337                         i < m_animated_meshnode->getMaterialCount(); ++i)
1338                         {
1339                                 // This allows setting per-material colors. However, until a real lighting
1340                                 // system is added, the code below will have no effect. Once MineTest
1341                                 // has directional lighting, it should work automatically.
1342                                 m_animated_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1343                                 m_animated_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1344                                 m_animated_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1345                         }
1346                 }
1347         }
1348
1349         else if (m_meshnode) {
1350                 if(m_prop.visual == "cube")
1351                 {
1352                         for (u32 i = 0; i < 6; ++i)
1353                         {
1354                                 std::string texturestring = "unknown_node.png";
1355                                 if(m_prop.textures.size() > i)
1356                                         texturestring = m_prop.textures[i];
1357                                 texturestring += mod;
1358
1359
1360                                 // Set material flags and texture
1361                                 video::SMaterial& material = m_meshnode->getMaterial(i);
1362                                 material.MaterialType = m_material_type;
1363                                 material.MaterialTypeParam = 0.5f;
1364                                 material.setFlag(video::EMF_LIGHTING, false);
1365                                 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1366                                 material.setTexture(0,
1367                                                 tsrc->getTextureForMesh(texturestring));
1368                                 material.getTextureMatrix(0).makeIdentity();
1369
1370                                 // This allows setting per-material colors. However, until a real lighting
1371                                 // system is added, the code below will have no effect. Once MineTest
1372                                 // has directional lighting, it should work automatically.
1373                                 if(m_prop.colors.size() > i)
1374                                 {
1375                                         m_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1376                                         m_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1377                                         m_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1378                                 }
1379
1380                                 m_meshnode->getMaterial(i).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1381                                 m_meshnode->getMaterial(i).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1382                                 m_meshnode->getMaterial(i).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1383                         }
1384                 } else if (m_prop.visual == "upright_sprite") {
1385                         scene::IMesh *mesh = m_meshnode->getMesh();
1386                         {
1387                                 std::string tname = "unknown_object.png";
1388                                 if (!m_prop.textures.empty())
1389                                         tname = m_prop.textures[0];
1390                                 tname += mod;
1391                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(0);
1392                                 buf->getMaterial().setTexture(0,
1393                                                 tsrc->getTextureForMesh(tname));
1394
1395                                 // This allows setting per-material colors. However, until a real lighting
1396                                 // system is added, the code below will have no effect. Once MineTest
1397                                 // has directional lighting, it should work automatically.
1398                                 if(!m_prop.colors.empty()) {
1399                                         buf->getMaterial().AmbientColor = m_prop.colors[0];
1400                                         buf->getMaterial().DiffuseColor = m_prop.colors[0];
1401                                         buf->getMaterial().SpecularColor = m_prop.colors[0];
1402                                 }
1403
1404                                 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1405                                 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1406                                 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1407                         }
1408                         {
1409                                 std::string tname = "unknown_object.png";
1410                                 if (m_prop.textures.size() >= 2)
1411                                         tname = m_prop.textures[1];
1412                                 else if (!m_prop.textures.empty())
1413                                         tname = m_prop.textures[0];
1414                                 tname += mod;
1415                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(1);
1416                                 buf->getMaterial().setTexture(0,
1417                                                 tsrc->getTextureForMesh(tname));
1418
1419                                 // This allows setting per-material colors. However, until a real lighting
1420                                 // system is added, the code below will have no effect. Once MineTest
1421                                 // has directional lighting, it should work automatically.
1422                                 if (m_prop.colors.size() >= 2) {
1423                                         buf->getMaterial().AmbientColor = m_prop.colors[1];
1424                                         buf->getMaterial().DiffuseColor = m_prop.colors[1];
1425                                         buf->getMaterial().SpecularColor = m_prop.colors[1];
1426                                 } else if (!m_prop.colors.empty()) {
1427                                         buf->getMaterial().AmbientColor = m_prop.colors[0];
1428                                         buf->getMaterial().DiffuseColor = m_prop.colors[0];
1429                                         buf->getMaterial().SpecularColor = m_prop.colors[0];
1430                                 }
1431
1432                                 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1433                                 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1434                                 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1435                         }
1436                         // Set mesh color (only if lighting is disabled)
1437                         if (!m_prop.colors.empty() && m_glow < 0)
1438                                 setMeshColor(mesh, m_prop.colors[0]);
1439                 }
1440         }
1441         // Prevent showing the player after changing texture
1442         if (m_is_local_player)
1443                 updateMeshCulling();
1444 }
1445
1446 void GenericCAO::updateAnimation()
1447 {
1448         if (!m_animated_meshnode)
1449                 return;
1450
1451         if (m_animated_meshnode->getStartFrame() != m_animation_range.X ||
1452                 m_animated_meshnode->getEndFrame() != m_animation_range.Y)
1453                         m_animated_meshnode->setFrameLoop(m_animation_range.X, m_animation_range.Y);
1454         if (m_animated_meshnode->getAnimationSpeed() != m_animation_speed)
1455                 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1456         m_animated_meshnode->setTransitionTime(m_animation_blend);
1457 // Requires Irrlicht 1.8 or greater
1458 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR > 1
1459         if (m_animated_meshnode->getLoopMode() != m_animation_loop)
1460                 m_animated_meshnode->setLoopMode(m_animation_loop);
1461 #endif
1462 }
1463
1464 void GenericCAO::updateAnimationSpeed()
1465 {
1466         if (!m_animated_meshnode)
1467                 return;
1468
1469         m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1470 }
1471
1472 void GenericCAO::updateBonePosition()
1473 {
1474         if (m_bone_position.empty() || !m_animated_meshnode)
1475                 return;
1476
1477         m_animated_meshnode->setJointMode(irr::scene::EJUOR_CONTROL); // To write positions to the mesh on render
1478         for (auto &it : m_bone_position) {
1479                 std::string bone_name = it.first;
1480                 irr::scene::IBoneSceneNode* bone = m_animated_meshnode->getJointNode(bone_name.c_str());
1481                 if (bone) {
1482                         bone->setPosition(it.second.X);
1483                         bone->setRotation(it.second.Y);
1484                 }
1485         }
1486
1487         // search through bones to find mistakenly rotated bones due to bug in Irrlicht
1488         for (u32 i = 0; i < m_animated_meshnode->getJointCount(); ++i) {
1489                 irr::scene::IBoneSceneNode *bone = m_animated_meshnode->getJointNode(i);
1490                 if (!bone)
1491                         continue;
1492
1493                 //If bone is manually positioned there is no need to perform the bug check
1494                 bool skip = false;
1495                 for (auto &it : m_bone_position) {
1496                         if (it.first == bone->getName()) {
1497                                 skip = true;
1498                                 break;
1499                         }
1500                 }
1501                 if (skip)
1502                         continue;
1503
1504                 // Workaround for Irrlicht bug
1505                 // We check each bone to see if it has been rotated ~180deg from its expected position due to a bug in Irricht
1506                 // when using EJUOR_CONTROL joint control. If the bug is detected we update the bone to the proper position
1507                 // and update the bones transformation.
1508                 v3f bone_rot = bone->getRelativeTransformation().getRotationDegrees();
1509                 float offset = fabsf(bone_rot.X - bone->getRotation().X);
1510                 if (offset > 179.9f && offset < 180.1f) {
1511                         bone->setRotation(bone_rot);
1512                         bone->updateAbsolutePosition();
1513                 }
1514         }
1515         // The following is needed for set_bone_pos to propagate to
1516         // attached objects correctly.
1517         // Irrlicht ought to do this, but doesn't when using EJUOR_CONTROL.
1518         for (u32 i = 0; i < m_animated_meshnode->getJointCount(); ++i) {
1519                 auto bone = m_animated_meshnode->getJointNode(i);
1520                 // Look for the root bone.
1521                 if (bone && bone->getParent() == m_animated_meshnode) {
1522                         // Update entire skeleton.
1523                         bone->updateAbsolutePositionOfAllChildren();
1524                         break;
1525                 }
1526         }
1527 }
1528
1529 void GenericCAO::updateAttachments()
1530 {
1531         ClientActiveObject *parent = getParent();
1532
1533         m_attached_to_local = parent && parent->isLocalPlayer();
1534
1535         /*
1536         Following cases exist:
1537                 m_attachment_parent_id == 0 && !parent
1538                         This object is not attached
1539                 m_attachment_parent_id != 0 && parent
1540                         This object is attached
1541                 m_attachment_parent_id != 0 && !parent
1542                         This object will be attached as soon the parent is known
1543                 m_attachment_parent_id == 0 && parent
1544                         Impossible case
1545         */
1546
1547         if (!parent) { // Detach or don't attach
1548                 if (m_matrixnode) {
1549                         v3s16 camera_offset = m_env->getCameraOffset();
1550                         v3f old_pos = getPosition();
1551
1552                         m_matrixnode->setParent(m_smgr->getRootSceneNode());
1553                         getPosRotMatrix().setTranslation(old_pos - intToFloat(camera_offset, BS));
1554                         m_matrixnode->updateAbsolutePosition();
1555                 }
1556         }
1557         else // Attach
1558         {
1559                 parent->updateAttachments();
1560                 scene::ISceneNode *parent_node = parent->getSceneNode();
1561                 scene::IAnimatedMeshSceneNode *parent_animated_mesh_node =
1562                                 parent->getAnimatedMeshSceneNode();
1563                 if (parent_animated_mesh_node && !m_attachment_bone.empty()) {
1564                         parent_node = parent_animated_mesh_node->getJointNode(m_attachment_bone.c_str());
1565                 }
1566
1567                 if (m_matrixnode && parent_node) {
1568                         m_matrixnode->setParent(parent_node);
1569                         parent_node->updateAbsolutePosition();
1570                         getPosRotMatrix().setTranslation(m_attachment_position);
1571                         //setPitchYawRoll(getPosRotMatrix(), m_attachment_rotation);
1572                         // use Irrlicht eulers instead
1573                         getPosRotMatrix().setRotationDegrees(m_attachment_rotation);
1574                         m_matrixnode->updateAbsolutePosition();
1575                 }
1576         }
1577 }
1578
1579 bool GenericCAO::visualExpiryRequired(const ObjectProperties &new_) const
1580 {
1581         const ObjectProperties &old = m_prop;
1582         /* Visuals do not need to be expired for:
1583          * - nametag props: handled by updateNametag()
1584          * - textures:      handled by updateTextures()
1585          * - sprite props:  handled by updateTexturePos()
1586          * - glow:          handled by updateLight()
1587          * - any other properties that do not change appearance
1588          */
1589
1590         bool uses_legacy_texture = new_.wield_item.empty() &&
1591                 (new_.visual == "wielditem" || new_.visual == "item");
1592         // Ordered to compare primitive types before std::vectors
1593         return old.backface_culling != new_.backface_culling ||
1594                 old.is_visible != new_.is_visible ||
1595                 old.mesh != new_.mesh ||
1596                 old.shaded != new_.shaded ||
1597                 old.use_texture_alpha != new_.use_texture_alpha ||
1598                 old.visual != new_.visual ||
1599                 old.visual_size != new_.visual_size ||
1600                 old.wield_item != new_.wield_item ||
1601                 old.colors != new_.colors ||
1602                 (uses_legacy_texture && old.textures != new_.textures);
1603 }
1604
1605 void GenericCAO::processMessage(const std::string &data)
1606 {
1607         //infostream<<"GenericCAO: Got message"<<std::endl;
1608         std::istringstream is(data, std::ios::binary);
1609         // command
1610         u8 cmd = readU8(is);
1611         if (cmd == AO_CMD_SET_PROPERTIES) {
1612                 ObjectProperties newprops;
1613                 newprops.show_on_minimap = m_is_player; // default
1614
1615                 newprops.deSerialize(is);
1616
1617                 // Check what exactly changed
1618                 bool expire_visuals = visualExpiryRequired(newprops);
1619                 bool textures_changed = m_prop.textures != newprops.textures;
1620
1621                 // Apply changes
1622                 m_prop = std::move(newprops);
1623
1624                 m_selection_box = m_prop.selectionbox;
1625                 m_selection_box.MinEdge *= BS;
1626                 m_selection_box.MaxEdge *= BS;
1627
1628                 m_tx_size.X = 1.0f / m_prop.spritediv.X;
1629                 m_tx_size.Y = 1.0f / m_prop.spritediv.Y;
1630
1631                 if(!m_initial_tx_basepos_set){
1632                         m_initial_tx_basepos_set = true;
1633                         m_tx_basepos = m_prop.initial_sprite_basepos;
1634                 }
1635                 if (m_is_local_player) {
1636                         LocalPlayer *player = m_env->getLocalPlayer();
1637                         player->makes_footstep_sound = m_prop.makes_footstep_sound;
1638                         aabb3f collision_box = m_prop.collisionbox;
1639                         collision_box.MinEdge *= BS;
1640                         collision_box.MaxEdge *= BS;
1641                         player->setCollisionbox(collision_box);
1642                         player->setEyeHeight(m_prop.eye_height);
1643                         player->setZoomFOV(m_prop.zoom_fov);
1644                 }
1645
1646                 if ((m_is_player && !m_is_local_player) && m_prop.nametag.empty())
1647                         m_prop.nametag = m_name;
1648                 if (m_is_local_player)
1649                         m_prop.show_on_minimap = false;
1650
1651                 if (expire_visuals) {
1652                         expireVisuals();
1653                 } else {
1654                         infostream << "GenericCAO: properties updated but expiring visuals"
1655                                 << " not necessary" << std::endl;
1656                         if (textures_changed) {
1657                                 // don't update while punch texture modifier is active
1658                                 if (m_reset_textures_timer < 0)
1659                                         updateTextures(m_current_texture_modifier);
1660                         }
1661                         updateNametag();
1662                         updateMarker();
1663                 }
1664         } else if (cmd == AO_CMD_UPDATE_POSITION) {
1665                 // Not sent by the server if this object is an attachment.
1666                 // We might however get here if the server notices the object being detached before the client.
1667                 m_position = readV3F32(is);
1668                 m_velocity = readV3F32(is);
1669                 m_acceleration = readV3F32(is);
1670                 m_rotation = readV3F32(is);
1671
1672                 m_rotation = wrapDegrees_0_360_v3f(m_rotation);
1673                 bool do_interpolate = readU8(is);
1674                 bool is_end_position = readU8(is);
1675                 float update_interval = readF32(is);
1676
1677                 // Place us a bit higher if we're physical, to not sink into
1678                 // the ground due to sucky collision detection...
1679                 if(m_prop.physical)
1680                         m_position += v3f(0,0.002,0);
1681
1682                 if(getParent() != NULL) // Just in case
1683                         return;
1684
1685                 if(do_interpolate)
1686                 {
1687                         if(!m_prop.physical)
1688                                 pos_translator.update(m_position, is_end_position, update_interval);
1689                 } else {
1690                         pos_translator.init(m_position);
1691                 }
1692                 rot_translator.update(m_rotation, false, update_interval);
1693                 updateNodePos();
1694         } else if (cmd == AO_CMD_SET_TEXTURE_MOD) {
1695                 std::string mod = deSerializeString16(is);
1696
1697                 // immediately reset a engine issued texture modifier if a mod sends a different one
1698                 if (m_reset_textures_timer > 0) {
1699                         m_reset_textures_timer = -1;
1700                         updateTextures(m_previous_texture_modifier);
1701                 }
1702                 updateTextures(mod);
1703         } else if (cmd == AO_CMD_SET_SPRITE) {
1704                 v2s16 p = readV2S16(is);
1705                 int num_frames = readU16(is);
1706                 float framelength = readF32(is);
1707                 bool select_horiz_by_yawpitch = readU8(is);
1708
1709                 m_tx_basepos = p;
1710                 m_anim_num_frames = num_frames;
1711                 m_anim_framelength = framelength;
1712                 m_tx_select_horiz_by_yawpitch = select_horiz_by_yawpitch;
1713
1714                 updateTexturePos();
1715         } else if (cmd == AO_CMD_SET_PHYSICS_OVERRIDE) {
1716                 float override_speed = readF32(is);
1717                 float override_jump = readF32(is);
1718                 float override_gravity = readF32(is);
1719                 // these are sent inverted so we get true when the server sends nothing
1720                 bool sneak = !readU8(is);
1721                 bool sneak_glitch = !readU8(is);
1722                 bool new_move = !readU8(is);
1723
1724
1725                 if(m_is_local_player)
1726                 {
1727                         LocalPlayer *player = m_env->getLocalPlayer();
1728                         player->physics_override_speed = override_speed;
1729                         player->physics_override_jump = override_jump;
1730                         player->physics_override_gravity = override_gravity;
1731                         player->physics_override_sneak = sneak;
1732                         player->physics_override_sneak_glitch = sneak_glitch;
1733                         player->physics_override_new_move = new_move;
1734                 }
1735         } else if (cmd == AO_CMD_SET_ANIMATION) {
1736                 // TODO: change frames send as v2s32 value
1737                 v2f range = readV2F32(is);
1738                 if (!m_is_local_player) {
1739                         m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1740                         m_animation_speed = readF32(is);
1741                         m_animation_blend = readF32(is);
1742                         // these are sent inverted so we get true when the server sends nothing
1743                         m_animation_loop = !readU8(is);
1744                         updateAnimation();
1745                 } else {
1746                         LocalPlayer *player = m_env->getLocalPlayer();
1747                         if(player->last_animation == NO_ANIM)
1748                         {
1749                                 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1750                                 m_animation_speed = readF32(is);
1751                                 m_animation_blend = readF32(is);
1752                                 // these are sent inverted so we get true when the server sends nothing
1753                                 m_animation_loop = !readU8(is);
1754                         }
1755                         // update animation only if local animations present
1756                         // and received animation is unknown (except idle animation)
1757                         bool is_known = false;
1758                         for (int i = 1;i<4;i++)
1759                         {
1760                                 if(m_animation_range.Y == player->local_animations[i].Y)
1761                                         is_known = true;
1762                         }
1763                         if(!is_known ||
1764                                         (player->local_animations[1].Y + player->local_animations[2].Y < 1))
1765                         {
1766                                         updateAnimation();
1767                         }
1768                 }
1769         } else if (cmd == AO_CMD_SET_ANIMATION_SPEED) {
1770                 m_animation_speed = readF32(is);
1771                 updateAnimationSpeed();
1772         } else if (cmd == AO_CMD_SET_BONE_POSITION) {
1773                 std::string bone = deSerializeString16(is);
1774                 v3f position = readV3F32(is);
1775                 v3f rotation = readV3F32(is);
1776                 m_bone_position[bone] = core::vector2d<v3f>(position, rotation);
1777
1778                 // updateBonePosition(); now called every step
1779         } else if (cmd == AO_CMD_ATTACH_TO) {
1780                 u16 parent_id = readS16(is);
1781                 std::string bone = deSerializeString16(is);
1782                 v3f position = readV3F32(is);
1783                 v3f rotation = readV3F32(is);
1784                 m_force_visible = readU8(is); // Returns false for EOF
1785
1786                 setAttachment(parent_id, bone, position, rotation);
1787
1788                 // Forcibly show attachments if required by set_attach
1789                 if (m_force_visible)
1790                         m_is_visible = true;
1791                 // localplayer itself can't be attached to localplayer
1792                 else if (!m_is_local_player) {
1793                         // Objects attached to the local player should be hidden in first
1794                         // person provided the forced boolean isn't set.
1795                         m_is_visible = !m_attached_to_local ||
1796                                 m_client->getCamera()->getCameraMode() != CAMERA_MODE_FIRST;
1797                         m_force_visible = false;
1798                 } else {
1799                         // Local players need to have this set,
1800                         // otherwise first person attachments fail.
1801                         m_is_visible = true;
1802                 }
1803         } else if (cmd == AO_CMD_PUNCHED) {
1804                 u16 result_hp = readU16(is);
1805
1806                 // Use this instead of the send damage to not interfere with prediction
1807                 s32 damage = (s32)m_hp - (s32)result_hp;
1808
1809                 m_hp = result_hp;
1810
1811                 if (m_is_local_player)
1812                         m_env->getLocalPlayer()->hp = m_hp;
1813
1814                 if (damage > 0)
1815                 {
1816                         if (m_hp == 0)
1817                         {
1818                                 // TODO: Execute defined fast response
1819                                 // As there is no definition, make a smoke puff
1820                                 ClientSimpleObject *simple = createSmokePuff(
1821                                                 m_smgr, m_env, m_position,
1822                                                 v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
1823                                 m_env->addSimpleObject(simple);
1824                         } else if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
1825                                 m_reset_textures_timer = 0.05;
1826                                 if(damage >= 2)
1827                                         m_reset_textures_timer += 0.05 * damage;
1828                                 updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
1829                         }
1830                 }
1831
1832                 if (m_hp == 0) {
1833                         // Same as 'Server::DiePlayer'
1834                         clearParentAttachment();
1835                         // Same as 'ObjectRef::l_remove'
1836                         if (!m_is_player)
1837                                 clearChildAttachments();
1838                 }
1839         } else if (cmd == AO_CMD_UPDATE_ARMOR_GROUPS) {
1840                 m_armor_groups.clear();
1841                 int armor_groups_size = readU16(is);
1842                 for(int i=0; i<armor_groups_size; i++)
1843                 {
1844                         std::string name = deSerializeString16(is);
1845                         int rating = readS16(is);
1846                         m_armor_groups[name] = rating;
1847                 }
1848         } else if (cmd == AO_CMD_SPAWN_INFANT) {
1849                 u16 child_id = readU16(is);
1850                 u8 type = readU8(is); // maybe this will be useful later
1851                 (void)type;
1852
1853                 addAttachmentChild(child_id);
1854         } else if (cmd == AO_CMD_OBSOLETE1) {
1855                 // Don't do anything and also don't log a warning
1856         } else {
1857                 warningstream << FUNCTION_NAME
1858                         << ": unknown command or outdated client \""
1859                         << +cmd << "\"" << std::endl;
1860         }
1861 }
1862
1863 /* \pre punchitem != NULL
1864  */
1865 bool GenericCAO::directReportPunch(v3f dir, const ItemStack *punchitem,
1866                 float time_from_last_punch)
1867 {
1868         assert(punchitem);      // pre-condition
1869         const ToolCapabilities *toolcap =
1870                         &punchitem->getToolCapabilities(m_client->idef());
1871         PunchDamageResult result = getPunchDamage(
1872                         m_armor_groups,
1873                         toolcap,
1874                         punchitem,
1875                         time_from_last_punch);
1876
1877         if(result.did_punch && result.damage != 0)
1878         {
1879                 if(result.damage < m_hp)
1880                 {
1881                         m_hp -= result.damage;
1882                 } else {
1883                         m_hp = 0;
1884                         // TODO: Execute defined fast response
1885                         // As there is no definition, make a smoke puff
1886                         ClientSimpleObject *simple = createSmokePuff(
1887                                         m_smgr, m_env, m_position,
1888                                         v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
1889                         m_env->addSimpleObject(simple);
1890                 }
1891                 if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
1892                         m_reset_textures_timer = 0.05;
1893                         if (result.damage >= 2)
1894                                 m_reset_textures_timer += 0.05 * result.damage;
1895                         updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
1896                 }
1897         }
1898
1899         return false;
1900 }
1901
1902 std::string GenericCAO::debugInfoText()
1903 {
1904         std::ostringstream os(std::ios::binary);
1905         os<<"GenericCAO hp="<<m_hp<<"\n";
1906         os<<"armor={";
1907         for(ItemGroupList::const_iterator i = m_armor_groups.begin();
1908                         i != m_armor_groups.end(); ++i)
1909         {
1910                 os<<i->first<<"="<<i->second<<", ";
1911         }
1912         os<<"}";
1913         return os.str();
1914 }
1915
1916 void GenericCAO::updateMeshCulling()
1917 {
1918         if (!m_is_local_player)
1919                 return;
1920
1921         // Grab the active player scene node so we know there's
1922         // at least a mesh to occlude from the camera.
1923         irr::scene::ISceneNode *node = getSceneNode();
1924         if (!node)
1925                 return;
1926
1927         if (m_client->getCamera()->getCameraMode() == CAMERA_MODE_FIRST) {
1928                 // Hide the mesh by culling both front and
1929                 // back faces. Serious hackyness but it works for our
1930                 // purposes. This also preserves the skeletal armature.
1931                 node->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
1932                         true);
1933                 node->setMaterialFlag(video::EMF_FRONT_FACE_CULLING,
1934                         true);
1935         } else {
1936                 // Restore mesh visibility.
1937                 node->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
1938                         m_prop.backface_culling);
1939                 node->setMaterialFlag(video::EMF_FRONT_FACE_CULLING,
1940                         false);
1941         }
1942 }
1943
1944 // Prototype
1945 GenericCAO proto_GenericCAO(NULL, NULL);