]> git.lizzy.rs Git - minetest.git/blob - src/client/content_cao.cpp
Irrlicht support code maintenance
[minetest.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->m_force_visible ? true : toset);
464                 }
465         }
466 }
467
468 void GenericCAO::setAttachment(int parent_id, const std::string &bone,
469                 v3f position, v3f rotation, bool force_visible)
470 {
471         int old_parent = m_attachment_parent_id;
472         m_attachment_parent_id = parent_id;
473         m_attachment_bone = bone;
474         m_attachment_position = position;
475         m_attachment_rotation = rotation;
476         m_force_visible = force_visible;
477
478         ClientActiveObject *parent = m_env->getActiveObject(parent_id);
479
480         if (parent_id != old_parent) {
481                 if (auto *o = m_env->getActiveObject(old_parent))
482                         o->removeAttachmentChild(m_id);
483                 if (parent)
484                         parent->addAttachmentChild(m_id);
485         }
486         updateAttachments();
487
488         // Forcibly show attachments if required by set_attach
489         if (m_force_visible) {
490                 m_is_visible = true;
491         } else if (!m_is_local_player) {
492                 // Objects attached to the local player should be hidden in first person
493                 m_is_visible = !m_attached_to_local ||
494                         m_client->getCamera()->getCameraMode() != CAMERA_MODE_FIRST;
495                 m_force_visible = false;
496         } else {
497                 // Local players need to have this set,
498                 // otherwise first person attachments fail.
499                 m_is_visible = true;
500         }
501 }
502
503 void GenericCAO::getAttachment(int *parent_id, std::string *bone, v3f *position,
504         v3f *rotation, bool *force_visible) const
505 {
506         *parent_id = m_attachment_parent_id;
507         *bone = m_attachment_bone;
508         *position = m_attachment_position;
509         *rotation = m_attachment_rotation;
510         *force_visible = m_force_visible;
511 }
512
513 void GenericCAO::clearChildAttachments()
514 {
515         // Cannot use for-loop here: setAttachment() modifies 'm_attachment_child_ids'!
516         while (!m_attachment_child_ids.empty()) {
517                 int child_id = *m_attachment_child_ids.begin();
518
519                 if (ClientActiveObject *child = m_env->getActiveObject(child_id))
520                         child->setAttachment(0, "", v3f(), v3f(), false);
521
522                 removeAttachmentChild(child_id);
523         }
524 }
525
526 void GenericCAO::clearParentAttachment()
527 {
528         if (m_attachment_parent_id)
529                 setAttachment(0, "", m_attachment_position, m_attachment_rotation, false);
530         else
531                 setAttachment(0, "", v3f(), v3f(), false);
532 }
533
534 void GenericCAO::addAttachmentChild(int child_id)
535 {
536         m_attachment_child_ids.insert(child_id);
537 }
538
539 void GenericCAO::removeAttachmentChild(int child_id)
540 {
541         m_attachment_child_ids.erase(child_id);
542 }
543
544 ClientActiveObject* GenericCAO::getParent() const
545 {
546         return m_attachment_parent_id ? m_env->getActiveObject(m_attachment_parent_id) :
547                         nullptr;
548 }
549
550 void GenericCAO::removeFromScene(bool permanent)
551 {
552         // Should be true when removing the object permanently
553         // and false when refreshing (eg: updating visuals)
554         if (m_env && permanent) {
555                 // The client does not know whether this object does re-appear to
556                 // a later time, thus do not clear child attachments.
557
558                 clearParentAttachment();
559         }
560
561         if (m_meshnode) {
562                 m_meshnode->remove();
563                 m_meshnode->drop();
564                 m_meshnode = nullptr;
565         } else if (m_animated_meshnode) {
566                 m_animated_meshnode->remove();
567                 m_animated_meshnode->drop();
568                 m_animated_meshnode = nullptr;
569         } else if (m_wield_meshnode) {
570                 m_wield_meshnode->remove();
571                 m_wield_meshnode->drop();
572                 m_wield_meshnode = nullptr;
573         } else if (m_spritenode) {
574                 m_spritenode->remove();
575                 m_spritenode->drop();
576                 m_spritenode = nullptr;
577         }
578
579         if (m_matrixnode) {
580                 m_matrixnode->remove();
581                 m_matrixnode->drop();
582                 m_matrixnode = nullptr;
583         }
584
585         if (m_nametag) {
586                 m_client->getCamera()->removeNametag(m_nametag);
587                 m_nametag = nullptr;
588         }
589
590         if (m_marker && m_client->getMinimap())
591                 m_client->getMinimap()->removeMarker(&m_marker);
592 }
593
594 void GenericCAO::addToScene(ITextureSource *tsrc)
595 {
596         m_smgr = RenderingEngine::get_scene_manager();
597
598         if (getSceneNode() != NULL) {
599                 return;
600         }
601
602         m_visuals_expired = false;
603
604         if (!m_prop.is_visible)
605                 return;
606
607         infostream << "GenericCAO::addToScene(): " << m_prop.visual << std::endl;
608
609         if (m_enable_shaders) {
610                 IShaderSource *shader_source = m_client->getShaderSource();
611                 MaterialType material_type;
612
613                 if (m_prop.shaded && m_prop.glow == 0)
614                         material_type = (m_prop.use_texture_alpha) ?
615                                 TILE_MATERIAL_ALPHA : TILE_MATERIAL_BASIC;
616                 else
617                         material_type = (m_prop.use_texture_alpha) ?
618                                 TILE_MATERIAL_PLAIN_ALPHA : TILE_MATERIAL_PLAIN;
619
620                 u32 shader_id = shader_source->getShader("object_shader", material_type, NDT_NORMAL);
621                 m_material_type = shader_source->getShaderInfo(shader_id).material;
622         } else {
623                 m_material_type = (m_prop.use_texture_alpha) ?
624                         video::EMT_TRANSPARENT_ALPHA_CHANNEL : video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
625         }
626
627         auto grabMatrixNode = [this] {
628                 m_matrixnode = RenderingEngine::get_scene_manager()->
629                                 addDummyTransformationSceneNode();
630                 m_matrixnode->grab();
631         };
632
633         auto setSceneNodeMaterial = [this] (scene::ISceneNode *node) {
634                 node->setMaterialFlag(video::EMF_LIGHTING, false);
635                 node->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
636                 node->setMaterialFlag(video::EMF_FOG_ENABLE, true);
637                 node->setMaterialType(m_material_type);
638
639                 if (m_enable_shaders) {
640                         node->setMaterialFlag(video::EMF_GOURAUD_SHADING, false);
641                         node->setMaterialFlag(video::EMF_NORMALIZE_NORMALS, true);
642                 }
643         };
644
645         if (m_prop.visual == "sprite") {
646                 grabMatrixNode();
647                 m_spritenode = RenderingEngine::get_scene_manager()->addBillboardSceneNode(
648                                 m_matrixnode, v2f(1, 1), v3f(0,0,0), -1);
649                 m_spritenode->grab();
650                 m_spritenode->setMaterialTexture(0,
651                                 tsrc->getTextureForMesh("unknown_node.png"));
652
653                 setSceneNodeMaterial(m_spritenode);
654
655                 m_spritenode->setSize(v2f(m_prop.visual_size.X,
656                                 m_prop.visual_size.Y) * BS);
657                 {
658                         const float txs = 1.0 / 1;
659                         const float tys = 1.0 / 1;
660                         setBillboardTextureMatrix(m_spritenode,
661                                         txs, tys, 0, 0);
662                 }
663         } else if (m_prop.visual == "upright_sprite") {
664                 grabMatrixNode();
665                 scene::SMesh *mesh = new scene::SMesh();
666                 double dx = BS * m_prop.visual_size.X / 2;
667                 double dy = BS * m_prop.visual_size.Y / 2;
668                 video::SColor c(0xFFFFFFFF);
669
670                 { // Front
671                         scene::IMeshBuffer *buf = new scene::SMeshBuffer();
672                         video::S3DVertex vertices[4] = {
673                                 video::S3DVertex(-dx, -dy, 0, 0,0,1, c, 1,1),
674                                 video::S3DVertex( dx, -dy, 0, 0,0,1, c, 0,1),
675                                 video::S3DVertex( dx,  dy, 0, 0,0,1, c, 0,0),
676                                 video::S3DVertex(-dx,  dy, 0, 0,0,1, c, 1,0),
677                         };
678                         if (m_is_player) {
679                                 // Move minimal Y position to 0 (feet position)
680                                 for (video::S3DVertex &vertex : vertices)
681                                         vertex.Pos.Y += dy;
682                         }
683                         u16 indices[] = {0,1,2,2,3,0};
684                         buf->append(vertices, 4, indices, 6);
685                         // Set material
686                         buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
687                         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
688                         buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
689                         buf->getMaterial().MaterialType = m_material_type;
690
691                         if (m_enable_shaders) {
692                                 buf->getMaterial().EmissiveColor = c;
693                                 buf->getMaterial().setFlag(video::EMF_GOURAUD_SHADING, false);
694                                 buf->getMaterial().setFlag(video::EMF_NORMALIZE_NORMALS, true);
695                         }
696
697                         // Add to mesh
698                         mesh->addMeshBuffer(buf);
699                         buf->drop();
700                 }
701                 { // Back
702                         scene::IMeshBuffer *buf = new scene::SMeshBuffer();
703                         video::S3DVertex vertices[4] = {
704                                 video::S3DVertex( dx,-dy, 0, 0,0,-1, c, 1,1),
705                                 video::S3DVertex(-dx,-dy, 0, 0,0,-1, c, 0,1),
706                                 video::S3DVertex(-dx, dy, 0, 0,0,-1, c, 0,0),
707                                 video::S3DVertex( dx, dy, 0, 0,0,-1, c, 1,0),
708                         };
709                         if (m_is_player) {
710                                 // Move minimal Y position to 0 (feet position)
711                                 for (video::S3DVertex &vertex : vertices)
712                                         vertex.Pos.Y += dy;
713                         }
714                         u16 indices[] = {0,1,2,2,3,0};
715                         buf->append(vertices, 4, indices, 6);
716                         // Set material
717                         buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
718                         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
719                         buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
720                         buf->getMaterial().MaterialType = m_material_type;
721
722                         if (m_enable_shaders) {
723                                 buf->getMaterial().EmissiveColor = c;
724                                 buf->getMaterial().setFlag(video::EMF_GOURAUD_SHADING, false);
725                                 buf->getMaterial().setFlag(video::EMF_NORMALIZE_NORMALS, true);
726                         }
727
728                         // Add to mesh
729                         mesh->addMeshBuffer(buf);
730                         buf->drop();
731                 }
732                 m_meshnode = RenderingEngine::get_scene_manager()->
733                         addMeshSceneNode(mesh, m_matrixnode);
734                 m_meshnode->grab();
735                 mesh->drop();
736                 // Set it to use the materials of the meshbuffers directly.
737                 // This is needed for changing the texture in the future
738                 m_meshnode->setReadOnlyMaterials(true);
739         } else if (m_prop.visual == "cube") {
740                 grabMatrixNode();
741                 scene::IMesh *mesh = createCubeMesh(v3f(BS,BS,BS));
742                 m_meshnode = RenderingEngine::get_scene_manager()->
743                         addMeshSceneNode(mesh, m_matrixnode);
744                 m_meshnode->grab();
745                 mesh->drop();
746
747                 m_meshnode->setScale(m_prop.visual_size);
748                 m_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
749                         m_prop.backface_culling);
750
751                 setSceneNodeMaterial(m_meshnode);
752         } else if (m_prop.visual == "mesh") {
753                 grabMatrixNode();
754                 scene::IAnimatedMesh *mesh = m_client->getMesh(m_prop.mesh, true);
755                 if (mesh) {
756                         m_animated_meshnode = RenderingEngine::get_scene_manager()->
757                                 addAnimatedMeshSceneNode(mesh, m_matrixnode);
758                         m_animated_meshnode->grab();
759                         mesh->drop(); // The scene node took hold of it
760
761                         if (!checkMeshNormals(mesh)) {
762                                 infostream << "GenericCAO: recalculating normals for mesh "
763                                         << m_prop.mesh << std::endl;
764                                 m_smgr->getMeshManipulator()->
765                                                 recalculateNormals(mesh, true, false);
766                         }
767
768                         m_animated_meshnode->animateJoints(); // Needed for some animations
769                         m_animated_meshnode->setScale(m_prop.visual_size);
770
771                         // set vertex colors to ensure alpha is set
772                         setMeshColor(m_animated_meshnode->getMesh(), video::SColor(0xFFFFFFFF));
773
774                         setAnimatedMeshColor(m_animated_meshnode, video::SColor(0xFFFFFFFF));
775
776                         setSceneNodeMaterial(m_animated_meshnode);
777
778                         m_animated_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
779                                 m_prop.backface_culling);
780                 } else
781                         errorstream<<"GenericCAO::addToScene(): Could not load mesh "<<m_prop.mesh<<std::endl;
782         } else if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
783                 grabMatrixNode();
784                 ItemStack item;
785                 if (m_prop.wield_item.empty()) {
786                         // Old format, only textures are specified.
787                         infostream << "textures: " << m_prop.textures.size() << std::endl;
788                         if (!m_prop.textures.empty()) {
789                                 infostream << "textures[0]: " << m_prop.textures[0]
790                                         << std::endl;
791                                 IItemDefManager *idef = m_client->idef();
792                                 item = ItemStack(m_prop.textures[0], 1, 0, idef);
793                         }
794                 } else {
795                         infostream << "serialized form: " << m_prop.wield_item << std::endl;
796                         item.deSerialize(m_prop.wield_item, m_client->idef());
797                 }
798                 m_wield_meshnode = new WieldMeshSceneNode(
799                         RenderingEngine::get_scene_manager(), -1);
800                 m_wield_meshnode->setItem(item, m_client,
801                         (m_prop.visual == "wielditem"));
802
803                 m_wield_meshnode->setScale(m_prop.visual_size / 2.0f);
804                 m_wield_meshnode->setColor(video::SColor(0xFFFFFFFF));
805         } else {
806                 infostream<<"GenericCAO::addToScene(): \""<<m_prop.visual
807                                 <<"\" not supported"<<std::endl;
808         }
809
810         /* don't update while punch texture modifier is active */
811         if (m_reset_textures_timer < 0)
812                 updateTextures(m_current_texture_modifier);
813
814         scene::ISceneNode *node = getSceneNode();
815
816         if (node && m_matrixnode)
817                 node->setParent(m_matrixnode);
818
819         updateNametag();
820         updateMarker();
821         updateNodePos();
822         updateAnimation();
823         updateBonePosition();
824         updateAttachments();
825         setNodeLight(m_last_light);
826         updateMeshCulling();
827 }
828
829 void GenericCAO::updateLight(u32 day_night_ratio)
830 {
831         if (m_glow < 0)
832                 return;
833
834         u8 light_at_pos = 0;
835         bool pos_ok = false;
836
837         v3s16 pos[3];
838         u16 npos = getLightPosition(pos);
839         for (u16 i = 0; i < npos; i++) {
840                 bool this_ok;
841                 MapNode n = m_env->getMap().getNode(pos[i], &this_ok);
842                 if (this_ok) {
843                         u8 this_light = n.getLightBlend(day_night_ratio, m_client->ndef());
844                         light_at_pos = MYMAX(light_at_pos, this_light);
845                         pos_ok = true;
846                 }
847         }
848         if (!pos_ok)
849                 light_at_pos = blend_light(day_night_ratio, LIGHT_SUN, 0);
850
851         u8 light = decode_light(light_at_pos + m_glow);
852         if (light != m_last_light) {
853                 m_last_light = light;
854                 setNodeLight(light);
855         }
856 }
857
858 void GenericCAO::setNodeLight(u8 light)
859 {
860         video::SColor color(255, light, light, light);
861
862         if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
863                 if (m_wield_meshnode)
864                         m_wield_meshnode->setNodeLightColor(color);
865                 return;
866         }
867
868         if (m_enable_shaders) {
869                 if (m_prop.visual == "upright_sprite") {
870                         if (!m_meshnode)
871                                 return;
872
873                         scene::IMesh *mesh = m_meshnode->getMesh();
874                         for (u32 i = 0; i < mesh->getMeshBufferCount(); ++i) {
875                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
876                                 buf->getMaterial().EmissiveColor = color;
877                         }
878                 } else {
879                         scene::ISceneNode *node = getSceneNode();
880                         if (!node)
881                                 return;
882
883                         for (u32 i = 0; i < node->getMaterialCount(); ++i) {
884                                 video::SMaterial &material = node->getMaterial(i);
885                                 material.EmissiveColor = color;
886                         }
887                 }
888         } else {
889                 if (m_meshnode) {
890                         setMeshColor(m_meshnode->getMesh(), color);
891                 } else if (m_animated_meshnode) {
892                         setAnimatedMeshColor(m_animated_meshnode, color);
893                 } else if (m_spritenode) {
894                         m_spritenode->setColor(color);
895                 }
896         }
897 }
898
899 u16 GenericCAO::getLightPosition(v3s16 *pos)
900 {
901         const auto &box = m_prop.collisionbox;
902         pos[0] = floatToInt(m_position + box.MinEdge * BS, BS);
903         pos[1] = floatToInt(m_position + box.MaxEdge * BS, BS);
904
905         // Skip center pos if it falls into the same node as Min or MaxEdge
906         if ((box.MaxEdge - box.MinEdge).getLengthSQ() < 3.0f)
907                 return 2;
908         pos[2] = floatToInt(m_position + box.getCenter() * BS, BS);
909         return 3;
910 }
911
912 void GenericCAO::updateMarker()
913 {
914         if (!m_client->getMinimap())
915                 return;
916
917         if (!m_prop.show_on_minimap) {
918                 if (m_marker)
919                         m_client->getMinimap()->removeMarker(&m_marker);
920                 return;
921         }
922
923         if (m_marker)
924                 return;
925
926         scene::ISceneNode *node = getSceneNode();
927         if (!node)
928                 return;
929         m_marker = m_client->getMinimap()->addMarker(node);
930 }
931
932 void GenericCAO::updateNametag()
933 {
934         if (m_is_local_player) // No nametag for local player
935                 return;
936
937         if (m_prop.nametag.empty() || m_prop.nametag_color.getAlpha() == 0) {
938                 // Delete nametag
939                 if (m_nametag) {
940                         m_client->getCamera()->removeNametag(m_nametag);
941                         m_nametag = nullptr;
942                 }
943                 return;
944         }
945
946         scene::ISceneNode *node = getSceneNode();
947         if (!node)
948                 return;
949
950         v3f pos;
951         pos.Y = m_prop.selectionbox.MaxEdge.Y + 0.3f;
952         if (!m_nametag) {
953                 // Add nametag
954                 m_nametag = m_client->getCamera()->addNametag(node,
955                         m_prop.nametag, m_prop.nametag_color,
956                         m_prop.nametag_bgcolor, pos);
957         } else {
958                 // Update nametag
959                 m_nametag->text = m_prop.nametag;
960                 m_nametag->textcolor = m_prop.nametag_color;
961                 m_nametag->bgcolor = m_prop.nametag_bgcolor;
962                 m_nametag->pos = pos;
963         }
964 }
965
966 void GenericCAO::updateNodePos()
967 {
968         if (getParent() != NULL)
969                 return;
970
971         scene::ISceneNode *node = getSceneNode();
972
973         if (node) {
974                 v3s16 camera_offset = m_env->getCameraOffset();
975                 v3f pos = pos_translator.val_current -
976                                 intToFloat(camera_offset, BS);
977                 getPosRotMatrix().setTranslation(pos);
978                 if (node != m_spritenode) { // rotate if not a sprite
979                         v3f rot = m_is_local_player ? -m_rotation : -rot_translator.val_current;
980                         setPitchYawRoll(getPosRotMatrix(), rot);
981                 }
982         }
983 }
984
985 void GenericCAO::step(float dtime, ClientEnvironment *env)
986 {
987         // Handle model animations and update positions instantly to prevent lags
988         if (m_is_local_player) {
989                 LocalPlayer *player = m_env->getLocalPlayer();
990                 m_position = player->getPosition();
991                 pos_translator.val_current = m_position;
992                 m_rotation.Y = wrapDegrees_0_360(player->getYaw());
993                 rot_translator.val_current = m_rotation;
994
995                 if (m_is_visible) {
996                         int old_anim = player->last_animation;
997                         float old_anim_speed = player->last_animation_speed;
998                         m_velocity = v3f(0,0,0);
999                         m_acceleration = v3f(0,0,0);
1000                         const PlayerControl &controls = player->getPlayerControl();
1001
1002                         bool walking = false;
1003                         if (controls.up || controls.down || controls.left || controls.right ||
1004                                         controls.forw_move_joystick_axis != 0.f ||
1005                                         controls.sidew_move_joystick_axis != 0.f)
1006                                 walking = true;
1007
1008                         f32 new_speed = player->local_animation_speed;
1009                         v2s32 new_anim = v2s32(0,0);
1010                         bool allow_update = false;
1011
1012                         // increase speed if using fast or flying fast
1013                         if((g_settings->getBool("fast_move") &&
1014                                         m_client->checkLocalPrivilege("fast")) &&
1015                                         (controls.aux1 ||
1016                                         (!player->touching_ground &&
1017                                         g_settings->getBool("free_move") &&
1018                                         m_client->checkLocalPrivilege("fly"))))
1019                                         new_speed *= 1.5;
1020                         // slowdown speed if sneeking
1021                         if (controls.sneak && walking)
1022                                 new_speed /= 2;
1023
1024                         if (walking && (controls.dig || controls.place)) {
1025                                 new_anim = player->local_animations[3];
1026                                 player->last_animation = WD_ANIM;
1027                         } else if (walking) {
1028                                 new_anim = player->local_animations[1];
1029                                 player->last_animation = WALK_ANIM;
1030                         } else if (controls.dig || controls.place) {
1031                                 new_anim = player->local_animations[2];
1032                                 player->last_animation = DIG_ANIM;
1033                         }
1034
1035                         // Apply animations if input detected and not attached
1036                         // or set idle animation
1037                         if ((new_anim.X + new_anim.Y) > 0 && !getParent()) {
1038                                 allow_update = true;
1039                                 m_animation_range = new_anim;
1040                                 m_animation_speed = new_speed;
1041                                 player->last_animation_speed = m_animation_speed;
1042                         } else {
1043                                 player->last_animation = NO_ANIM;
1044
1045                                 if (old_anim != NO_ANIM) {
1046                                         m_animation_range = player->local_animations[0];
1047                                         updateAnimation();
1048                                 }
1049                         }
1050
1051                         // Update local player animations
1052                         if ((player->last_animation != old_anim ||
1053                                         m_animation_speed != old_anim_speed) &&
1054                                         player->last_animation != NO_ANIM && allow_update)
1055                                 updateAnimation();
1056
1057                 }
1058         }
1059
1060         if (m_visuals_expired && m_smgr) {
1061                 m_visuals_expired = false;
1062
1063                 // Attachments, part 1: All attached objects must be unparented first,
1064                 // or Irrlicht causes a segmentation fault
1065                 for (u16 cao_id : m_attachment_child_ids) {
1066                         ClientActiveObject *obj = m_env->getActiveObject(cao_id);
1067                         if (obj) {
1068                                 scene::ISceneNode *child_node = obj->getSceneNode();
1069                                 // The node's parent is always an IDummyTraformationSceneNode,
1070                                 // so we need to reparent that one instead.
1071                                 if (child_node)
1072                                         child_node->getParent()->setParent(m_smgr->getRootSceneNode());
1073                         }
1074                 }
1075
1076                 removeFromScene(false);
1077                 addToScene(m_client->tsrc());
1078
1079                 // Attachments, part 2: Now that the parent has been refreshed, put its attachments back
1080                 for (u16 cao_id : m_attachment_child_ids) {
1081                         ClientActiveObject *obj = m_env->getActiveObject(cao_id);
1082                         if (obj)
1083                                 obj->updateAttachments();
1084                 }
1085         }
1086
1087         // Make sure m_is_visible is always applied
1088         scene::ISceneNode *node = getSceneNode();
1089         if (node)
1090                 node->setVisible(m_is_visible);
1091
1092         if(getParent() != NULL) // Attachments should be glued to their parent by Irrlicht
1093         {
1094                 // Set these for later
1095                 m_position = getPosition();
1096                 m_velocity = v3f(0,0,0);
1097                 m_acceleration = v3f(0,0,0);
1098                 pos_translator.val_current = m_position;
1099                 pos_translator.val_target = m_position;
1100         } else {
1101                 rot_translator.translate(dtime);
1102                 v3f lastpos = pos_translator.val_current;
1103
1104                 if(m_prop.physical)
1105                 {
1106                         aabb3f box = m_prop.collisionbox;
1107                         box.MinEdge *= BS;
1108                         box.MaxEdge *= BS;
1109                         collisionMoveResult moveresult;
1110                         f32 pos_max_d = BS*0.125; // Distance per iteration
1111                         v3f p_pos = m_position;
1112                         v3f p_velocity = m_velocity;
1113                         moveresult = collisionMoveSimple(env,env->getGameDef(),
1114                                         pos_max_d, box, m_prop.stepheight, dtime,
1115                                         &p_pos, &p_velocity, m_acceleration,
1116                                         this, m_prop.collideWithObjects);
1117                         // Apply results
1118                         m_position = p_pos;
1119                         m_velocity = p_velocity;
1120
1121                         bool is_end_position = moveresult.collides;
1122                         pos_translator.update(m_position, is_end_position, dtime);
1123                 } else {
1124                         m_position += dtime * m_velocity + 0.5 * dtime * dtime * m_acceleration;
1125                         m_velocity += dtime * m_acceleration;
1126                         pos_translator.update(m_position, pos_translator.aim_is_end,
1127                                         pos_translator.anim_time);
1128                 }
1129                 pos_translator.translate(dtime);
1130                 updateNodePos();
1131
1132                 float moved = lastpos.getDistanceFrom(pos_translator.val_current);
1133                 m_step_distance_counter += moved;
1134                 if (m_step_distance_counter > 1.5f * BS) {
1135                         m_step_distance_counter = 0.0f;
1136                         if (!m_is_local_player && m_prop.makes_footstep_sound) {
1137                                 const NodeDefManager *ndef = m_client->ndef();
1138                                 v3s16 p = floatToInt(getPosition() +
1139                                         v3f(0.0f, (m_prop.collisionbox.MinEdge.Y - 0.5f) * BS, 0.0f), BS);
1140                                 MapNode n = m_env->getMap().getNode(p);
1141                                 SimpleSoundSpec spec = ndef->get(n).sound_footstep;
1142                                 // Reduce footstep gain, as non-local-player footsteps are
1143                                 // somehow louder.
1144                                 spec.gain *= 0.6f;
1145                                 m_client->sound()->playSoundAt(spec, false, getPosition());
1146                         }
1147                 }
1148         }
1149
1150         m_anim_timer += dtime;
1151         if(m_anim_timer >= m_anim_framelength)
1152         {
1153                 m_anim_timer -= m_anim_framelength;
1154                 m_anim_frame++;
1155                 if(m_anim_frame >= m_anim_num_frames)
1156                         m_anim_frame = 0;
1157         }
1158
1159         updateTexturePos();
1160
1161         if(m_reset_textures_timer >= 0)
1162         {
1163                 m_reset_textures_timer -= dtime;
1164                 if(m_reset_textures_timer <= 0) {
1165                         m_reset_textures_timer = -1;
1166                         updateTextures(m_previous_texture_modifier);
1167                 }
1168         }
1169
1170         if (!getParent() && node && fabs(m_prop.automatic_rotate) > 0.001f) {
1171                 // This is the child node's rotation. It is only used for automatic_rotate.
1172                 v3f local_rot = node->getRotation();
1173                 local_rot.Y = modulo360f(local_rot.Y - dtime * core::RADTODEG *
1174                                 m_prop.automatic_rotate);
1175                 node->setRotation(local_rot);
1176         }
1177
1178         if (!getParent() && m_prop.automatic_face_movement_dir &&
1179                         (fabs(m_velocity.Z) > 0.001f || fabs(m_velocity.X) > 0.001f)) {
1180                 float target_yaw = atan2(m_velocity.Z, m_velocity.X) * 180 / M_PI
1181                                 + m_prop.automatic_face_movement_dir_offset;
1182                 float max_rotation_per_sec =
1183                                 m_prop.automatic_face_movement_max_rotation_per_sec;
1184
1185                 if (max_rotation_per_sec > 0) {
1186                         wrappedApproachShortest(m_rotation.Y, target_yaw,
1187                                 dtime * max_rotation_per_sec, 360.f);
1188                 } else {
1189                         // Negative values of max_rotation_per_sec mean disabled.
1190                         m_rotation.Y = target_yaw;
1191                 }
1192
1193                 rot_translator.val_current = m_rotation;
1194                 updateNodePos();
1195         }
1196
1197         if (m_animated_meshnode) {
1198                 // Everything must be updated; the whole transform
1199                 // chain as well as the animated mesh node.
1200                 // Otherwise, bone attachments would be relative to
1201                 // a position that's one frame old.
1202                 if (m_matrixnode)
1203                         updatePositionRecursive(m_matrixnode);
1204                 m_animated_meshnode->updateAbsolutePosition();
1205                 m_animated_meshnode->animateJoints();
1206                 updateBonePosition();
1207         }
1208 }
1209
1210 void GenericCAO::updateTexturePos()
1211 {
1212         if(m_spritenode)
1213         {
1214                 scene::ICameraSceneNode* camera =
1215                                 m_spritenode->getSceneManager()->getActiveCamera();
1216                 if(!camera)
1217                         return;
1218                 v3f cam_to_entity = m_spritenode->getAbsolutePosition()
1219                                 - camera->getAbsolutePosition();
1220                 cam_to_entity.normalize();
1221
1222                 int row = m_tx_basepos.Y;
1223                 int col = m_tx_basepos.X;
1224
1225                 // Yawpitch goes rightwards
1226                 if (m_tx_select_horiz_by_yawpitch) {
1227                         if (cam_to_entity.Y > 0.75)
1228                                 col += 5;
1229                         else if (cam_to_entity.Y < -0.75)
1230                                 col += 4;
1231                         else {
1232                                 float mob_dir =
1233                                                 atan2(cam_to_entity.Z, cam_to_entity.X) / M_PI * 180.;
1234                                 float dir = mob_dir - m_rotation.Y;
1235                                 dir = wrapDegrees_180(dir);
1236                                 if (std::fabs(wrapDegrees_180(dir - 0)) <= 45.1f)
1237                                         col += 2;
1238                                 else if(std::fabs(wrapDegrees_180(dir - 90)) <= 45.1f)
1239                                         col += 3;
1240                                 else if(std::fabs(wrapDegrees_180(dir - 180)) <= 45.1f)
1241                                         col += 0;
1242                                 else if(std::fabs(wrapDegrees_180(dir + 90)) <= 45.1f)
1243                                         col += 1;
1244                                 else
1245                                         col += 4;
1246                         }
1247                 }
1248
1249                 // Animation goes downwards
1250                 row += m_anim_frame;
1251
1252                 float txs = m_tx_size.X;
1253                 float tys = m_tx_size.Y;
1254                 setBillboardTextureMatrix(m_spritenode, txs, tys, col, row);
1255         }
1256
1257         else if (m_meshnode) {
1258                 if (m_prop.visual == "upright_sprite") {
1259                         int row = m_tx_basepos.Y;
1260                         int col = m_tx_basepos.X;
1261
1262                         // Animation goes downwards
1263                         row += m_anim_frame;
1264
1265                         const auto &tx = m_tx_size;
1266                         v2f t[4] = { // cf. vertices in GenericCAO::addToScene()
1267                                 tx * v2f(col+1, row+1),
1268                                 tx * v2f(col, row+1),
1269                                 tx * v2f(col, row),
1270                                 tx * v2f(col+1, row),
1271                         };
1272                         auto mesh = m_meshnode->getMesh();
1273                         setMeshBufferTextureCoords(mesh->getMeshBuffer(0), t, 4);
1274                         setMeshBufferTextureCoords(mesh->getMeshBuffer(1), t, 4);
1275                 }
1276         }
1277 }
1278
1279 // Do not pass by reference, see header.
1280 void GenericCAO::updateTextures(std::string mod)
1281 {
1282         ITextureSource *tsrc = m_client->tsrc();
1283
1284         bool use_trilinear_filter = g_settings->getBool("trilinear_filter");
1285         bool use_bilinear_filter = g_settings->getBool("bilinear_filter");
1286         bool use_anisotropic_filter = g_settings->getBool("anisotropic_filter");
1287
1288         m_previous_texture_modifier = m_current_texture_modifier;
1289         m_current_texture_modifier = mod;
1290         m_glow = m_prop.glow;
1291
1292         if (m_spritenode) {
1293                 if (m_prop.visual == "sprite") {
1294                         std::string texturestring = "unknown_node.png";
1295                         if (!m_prop.textures.empty())
1296                                 texturestring = m_prop.textures[0];
1297                         texturestring += mod;
1298                         m_spritenode->getMaterial(0).MaterialType = m_material_type;
1299                         m_spritenode->getMaterial(0).MaterialTypeParam = 0.5f;
1300                         m_spritenode->setMaterialTexture(0,
1301                                         tsrc->getTextureForMesh(texturestring));
1302
1303                         // This allows setting per-material colors. However, until a real lighting
1304                         // system is added, the code below will have no effect. Once MineTest
1305                         // has directional lighting, it should work automatically.
1306                         if (!m_prop.colors.empty()) {
1307                                 m_spritenode->getMaterial(0).AmbientColor = m_prop.colors[0];
1308                                 m_spritenode->getMaterial(0).DiffuseColor = m_prop.colors[0];
1309                                 m_spritenode->getMaterial(0).SpecularColor = m_prop.colors[0];
1310                         }
1311
1312                         m_spritenode->getMaterial(0).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1313                         m_spritenode->getMaterial(0).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1314                         m_spritenode->getMaterial(0).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1315                 }
1316         }
1317
1318         else if (m_animated_meshnode) {
1319                 if (m_prop.visual == "mesh") {
1320                         for (u32 i = 0; i < m_prop.textures.size() &&
1321                                         i < m_animated_meshnode->getMaterialCount(); ++i) {
1322                                 std::string texturestring = m_prop.textures[i];
1323                                 if (texturestring.empty())
1324                                         continue; // Empty texture string means don't modify that material
1325                                 texturestring += mod;
1326                                 video::ITexture* texture = tsrc->getTextureForMesh(texturestring);
1327                                 if (!texture) {
1328                                         errorstream<<"GenericCAO::updateTextures(): Could not load texture "<<texturestring<<std::endl;
1329                                         continue;
1330                                 }
1331
1332                                 // Set material flags and texture
1333                                 video::SMaterial& material = m_animated_meshnode->getMaterial(i);
1334                                 material.MaterialType = m_material_type;
1335                                 material.MaterialTypeParam = 0.5f;
1336                                 material.TextureLayer[0].Texture = texture;
1337                                 material.setFlag(video::EMF_LIGHTING, true);
1338                                 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1339                                 material.setFlag(video::EMF_BACK_FACE_CULLING, m_prop.backface_culling);
1340
1341                                 // don't filter low-res textures, makes them look blurry
1342                                 // player models have a res of 64
1343                                 const core::dimension2d<u32> &size = texture->getOriginalSize();
1344                                 const u32 res = std::min(size.Height, size.Width);
1345                                 use_trilinear_filter &= res > 64;
1346                                 use_bilinear_filter &= res > 64;
1347
1348                                 m_animated_meshnode->getMaterial(i)
1349                                                 .setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1350                                 m_animated_meshnode->getMaterial(i)
1351                                                 .setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1352                                 m_animated_meshnode->getMaterial(i)
1353                                                 .setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1354                         }
1355                         for (u32 i = 0; i < m_prop.colors.size() &&
1356                         i < m_animated_meshnode->getMaterialCount(); ++i)
1357                         {
1358                                 // This allows setting per-material colors. However, until a real lighting
1359                                 // system is added, the code below will have no effect. Once MineTest
1360                                 // has directional lighting, it should work automatically.
1361                                 m_animated_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1362                                 m_animated_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1363                                 m_animated_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1364                         }
1365                 }
1366         }
1367
1368         else if (m_meshnode) {
1369                 if(m_prop.visual == "cube")
1370                 {
1371                         for (u32 i = 0; i < 6; ++i)
1372                         {
1373                                 std::string texturestring = "unknown_node.png";
1374                                 if(m_prop.textures.size() > i)
1375                                         texturestring = m_prop.textures[i];
1376                                 texturestring += mod;
1377
1378
1379                                 // Set material flags and texture
1380                                 video::SMaterial& material = m_meshnode->getMaterial(i);
1381                                 material.MaterialType = m_material_type;
1382                                 material.MaterialTypeParam = 0.5f;
1383                                 material.setFlag(video::EMF_LIGHTING, false);
1384                                 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1385                                 material.setTexture(0,
1386                                                 tsrc->getTextureForMesh(texturestring));
1387                                 material.getTextureMatrix(0).makeIdentity();
1388
1389                                 // This allows setting per-material colors. However, until a real lighting
1390                                 // system is added, the code below will have no effect. Once MineTest
1391                                 // has directional lighting, it should work automatically.
1392                                 if(m_prop.colors.size() > i)
1393                                 {
1394                                         m_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1395                                         m_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1396                                         m_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1397                                 }
1398
1399                                 m_meshnode->getMaterial(i).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1400                                 m_meshnode->getMaterial(i).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1401                                 m_meshnode->getMaterial(i).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1402                         }
1403                 } else if (m_prop.visual == "upright_sprite") {
1404                         scene::IMesh *mesh = m_meshnode->getMesh();
1405                         {
1406                                 std::string tname = "unknown_object.png";
1407                                 if (!m_prop.textures.empty())
1408                                         tname = m_prop.textures[0];
1409                                 tname += mod;
1410                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(0);
1411                                 buf->getMaterial().setTexture(0,
1412                                                 tsrc->getTextureForMesh(tname));
1413
1414                                 // This allows setting per-material colors. However, until a real lighting
1415                                 // system is added, the code below will have no effect. Once MineTest
1416                                 // has directional lighting, it should work automatically.
1417                                 if(!m_prop.colors.empty()) {
1418                                         buf->getMaterial().AmbientColor = m_prop.colors[0];
1419                                         buf->getMaterial().DiffuseColor = m_prop.colors[0];
1420                                         buf->getMaterial().SpecularColor = m_prop.colors[0];
1421                                 }
1422
1423                                 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1424                                 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1425                                 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1426                         }
1427                         {
1428                                 std::string tname = "unknown_object.png";
1429                                 if (m_prop.textures.size() >= 2)
1430                                         tname = m_prop.textures[1];
1431                                 else if (!m_prop.textures.empty())
1432                                         tname = m_prop.textures[0];
1433                                 tname += mod;
1434                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(1);
1435                                 buf->getMaterial().setTexture(0,
1436                                                 tsrc->getTextureForMesh(tname));
1437
1438                                 // This allows setting per-material colors. However, until a real lighting
1439                                 // system is added, the code below will have no effect. Once MineTest
1440                                 // has directional lighting, it should work automatically.
1441                                 if (m_prop.colors.size() >= 2) {
1442                                         buf->getMaterial().AmbientColor = m_prop.colors[1];
1443                                         buf->getMaterial().DiffuseColor = m_prop.colors[1];
1444                                         buf->getMaterial().SpecularColor = m_prop.colors[1];
1445                                 } else if (!m_prop.colors.empty()) {
1446                                         buf->getMaterial().AmbientColor = m_prop.colors[0];
1447                                         buf->getMaterial().DiffuseColor = m_prop.colors[0];
1448                                         buf->getMaterial().SpecularColor = m_prop.colors[0];
1449                                 }
1450
1451                                 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1452                                 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1453                                 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1454                         }
1455                         // Set mesh color (only if lighting is disabled)
1456                         if (!m_prop.colors.empty() && m_glow < 0)
1457                                 setMeshColor(mesh, m_prop.colors[0]);
1458                 }
1459         }
1460         // Prevent showing the player after changing texture
1461         if (m_is_local_player)
1462                 updateMeshCulling();
1463 }
1464
1465 void GenericCAO::updateAnimation()
1466 {
1467         if (!m_animated_meshnode)
1468                 return;
1469
1470         if (m_animated_meshnode->getStartFrame() != m_animation_range.X ||
1471                 m_animated_meshnode->getEndFrame() != m_animation_range.Y)
1472                         m_animated_meshnode->setFrameLoop(m_animation_range.X, m_animation_range.Y);
1473         if (m_animated_meshnode->getAnimationSpeed() != m_animation_speed)
1474                 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1475         m_animated_meshnode->setTransitionTime(m_animation_blend);
1476         if (m_animated_meshnode->getLoopMode() != m_animation_loop)
1477                 m_animated_meshnode->setLoopMode(m_animation_loop);
1478 }
1479
1480 void GenericCAO::updateAnimationSpeed()
1481 {
1482         if (!m_animated_meshnode)
1483                 return;
1484
1485         m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1486 }
1487
1488 void GenericCAO::updateBonePosition()
1489 {
1490         if (m_bone_position.empty() || !m_animated_meshnode)
1491                 return;
1492
1493         m_animated_meshnode->setJointMode(irr::scene::EJUOR_CONTROL); // To write positions to the mesh on render
1494         for (auto &it : m_bone_position) {
1495                 std::string bone_name = it.first;
1496                 irr::scene::IBoneSceneNode* bone = m_animated_meshnode->getJointNode(bone_name.c_str());
1497                 if (bone) {
1498                         bone->setPosition(it.second.X);
1499                         bone->setRotation(it.second.Y);
1500                 }
1501         }
1502
1503         // search through bones to find mistakenly rotated bones due to bug in Irrlicht
1504         for (u32 i = 0; i < m_animated_meshnode->getJointCount(); ++i) {
1505                 irr::scene::IBoneSceneNode *bone = m_animated_meshnode->getJointNode(i);
1506                 if (!bone)
1507                         continue;
1508
1509                 //If bone is manually positioned there is no need to perform the bug check
1510                 bool skip = false;
1511                 for (auto &it : m_bone_position) {
1512                         if (it.first == bone->getName()) {
1513                                 skip = true;
1514                                 break;
1515                         }
1516                 }
1517                 if (skip)
1518                         continue;
1519
1520                 // Workaround for Irrlicht bug
1521                 // We check each bone to see if it has been rotated ~180deg from its expected position due to a bug in Irricht
1522                 // when using EJUOR_CONTROL joint control. If the bug is detected we update the bone to the proper position
1523                 // and update the bones transformation.
1524                 v3f bone_rot = bone->getRelativeTransformation().getRotationDegrees();
1525                 float offset = fabsf(bone_rot.X - bone->getRotation().X);
1526                 if (offset > 179.9f && offset < 180.1f) {
1527                         bone->setRotation(bone_rot);
1528                         bone->updateAbsolutePosition();
1529                 }
1530         }
1531         // The following is needed for set_bone_pos to propagate to
1532         // attached objects correctly.
1533         // Irrlicht ought to do this, but doesn't when using EJUOR_CONTROL.
1534         for (u32 i = 0; i < m_animated_meshnode->getJointCount(); ++i) {
1535                 auto bone = m_animated_meshnode->getJointNode(i);
1536                 // Look for the root bone.
1537                 if (bone && bone->getParent() == m_animated_meshnode) {
1538                         // Update entire skeleton.
1539                         bone->updateAbsolutePositionOfAllChildren();
1540                         break;
1541                 }
1542         }
1543 }
1544
1545 void GenericCAO::updateAttachments()
1546 {
1547         ClientActiveObject *parent = getParent();
1548
1549         m_attached_to_local = parent && parent->isLocalPlayer();
1550
1551         /*
1552         Following cases exist:
1553                 m_attachment_parent_id == 0 && !parent
1554                         This object is not attached
1555                 m_attachment_parent_id != 0 && parent
1556                         This object is attached
1557                 m_attachment_parent_id != 0 && !parent
1558                         This object will be attached as soon the parent is known
1559                 m_attachment_parent_id == 0 && parent
1560                         Impossible case
1561         */
1562
1563         if (!parent) { // Detach or don't attach
1564                 if (m_matrixnode) {
1565                         v3s16 camera_offset = m_env->getCameraOffset();
1566                         v3f old_pos = getPosition();
1567
1568                         m_matrixnode->setParent(m_smgr->getRootSceneNode());
1569                         getPosRotMatrix().setTranslation(old_pos - intToFloat(camera_offset, BS));
1570                         m_matrixnode->updateAbsolutePosition();
1571                 }
1572         }
1573         else // Attach
1574         {
1575                 parent->updateAttachments();
1576                 scene::ISceneNode *parent_node = parent->getSceneNode();
1577                 scene::IAnimatedMeshSceneNode *parent_animated_mesh_node =
1578                                 parent->getAnimatedMeshSceneNode();
1579                 if (parent_animated_mesh_node && !m_attachment_bone.empty()) {
1580                         parent_node = parent_animated_mesh_node->getJointNode(m_attachment_bone.c_str());
1581                 }
1582
1583                 if (m_matrixnode && parent_node) {
1584                         m_matrixnode->setParent(parent_node);
1585                         parent_node->updateAbsolutePosition();
1586                         getPosRotMatrix().setTranslation(m_attachment_position);
1587                         //setPitchYawRoll(getPosRotMatrix(), m_attachment_rotation);
1588                         // use Irrlicht eulers instead
1589                         getPosRotMatrix().setRotationDegrees(m_attachment_rotation);
1590                         m_matrixnode->updateAbsolutePosition();
1591                 }
1592         }
1593 }
1594
1595 bool GenericCAO::visualExpiryRequired(const ObjectProperties &new_) const
1596 {
1597         const ObjectProperties &old = m_prop;
1598         /* Visuals do not need to be expired for:
1599          * - nametag props: handled by updateNametag()
1600          * - textures:      handled by updateTextures()
1601          * - sprite props:  handled by updateTexturePos()
1602          * - glow:          handled by updateLight()
1603          * - any other properties that do not change appearance
1604          */
1605
1606         bool uses_legacy_texture = new_.wield_item.empty() &&
1607                 (new_.visual == "wielditem" || new_.visual == "item");
1608         // Ordered to compare primitive types before std::vectors
1609         return old.backface_culling != new_.backface_culling ||
1610                 old.is_visible != new_.is_visible ||
1611                 old.mesh != new_.mesh ||
1612                 old.shaded != new_.shaded ||
1613                 old.use_texture_alpha != new_.use_texture_alpha ||
1614                 old.visual != new_.visual ||
1615                 old.visual_size != new_.visual_size ||
1616                 old.wield_item != new_.wield_item ||
1617                 old.colors != new_.colors ||
1618                 (uses_legacy_texture && old.textures != new_.textures);
1619 }
1620
1621 void GenericCAO::processMessage(const std::string &data)
1622 {
1623         //infostream<<"GenericCAO: Got message"<<std::endl;
1624         std::istringstream is(data, std::ios::binary);
1625         // command
1626         u8 cmd = readU8(is);
1627         if (cmd == AO_CMD_SET_PROPERTIES) {
1628                 ObjectProperties newprops;
1629                 newprops.show_on_minimap = m_is_player; // default
1630
1631                 newprops.deSerialize(is);
1632
1633                 // Check what exactly changed
1634                 bool expire_visuals = visualExpiryRequired(newprops);
1635                 bool textures_changed = m_prop.textures != newprops.textures;
1636
1637                 // Apply changes
1638                 m_prop = std::move(newprops);
1639
1640                 m_selection_box = m_prop.selectionbox;
1641                 m_selection_box.MinEdge *= BS;
1642                 m_selection_box.MaxEdge *= BS;
1643
1644                 m_tx_size.X = 1.0f / m_prop.spritediv.X;
1645                 m_tx_size.Y = 1.0f / m_prop.spritediv.Y;
1646
1647                 if(!m_initial_tx_basepos_set){
1648                         m_initial_tx_basepos_set = true;
1649                         m_tx_basepos = m_prop.initial_sprite_basepos;
1650                 }
1651                 if (m_is_local_player) {
1652                         LocalPlayer *player = m_env->getLocalPlayer();
1653                         player->makes_footstep_sound = m_prop.makes_footstep_sound;
1654                         aabb3f collision_box = m_prop.collisionbox;
1655                         collision_box.MinEdge *= BS;
1656                         collision_box.MaxEdge *= BS;
1657                         player->setCollisionbox(collision_box);
1658                         player->setEyeHeight(m_prop.eye_height);
1659                         player->setZoomFOV(m_prop.zoom_fov);
1660                 }
1661
1662                 if ((m_is_player && !m_is_local_player) && m_prop.nametag.empty())
1663                         m_prop.nametag = m_name;
1664                 if (m_is_local_player)
1665                         m_prop.show_on_minimap = false;
1666
1667                 if (expire_visuals) {
1668                         expireVisuals();
1669                 } else {
1670                         infostream << "GenericCAO: properties updated but expiring visuals"
1671                                 << " not necessary" << std::endl;
1672                         if (textures_changed) {
1673                                 // don't update while punch texture modifier is active
1674                                 if (m_reset_textures_timer < 0)
1675                                         updateTextures(m_current_texture_modifier);
1676                         }
1677                         updateNametag();
1678                         updateMarker();
1679                 }
1680         } else if (cmd == AO_CMD_UPDATE_POSITION) {
1681                 // Not sent by the server if this object is an attachment.
1682                 // We might however get here if the server notices the object being detached before the client.
1683                 m_position = readV3F32(is);
1684                 m_velocity = readV3F32(is);
1685                 m_acceleration = readV3F32(is);
1686                 m_rotation = readV3F32(is);
1687
1688                 m_rotation = wrapDegrees_0_360_v3f(m_rotation);
1689                 bool do_interpolate = readU8(is);
1690                 bool is_end_position = readU8(is);
1691                 float update_interval = readF32(is);
1692
1693                 // Place us a bit higher if we're physical, to not sink into
1694                 // the ground due to sucky collision detection...
1695                 if(m_prop.physical)
1696                         m_position += v3f(0,0.002,0);
1697
1698                 if(getParent() != NULL) // Just in case
1699                         return;
1700
1701                 if(do_interpolate)
1702                 {
1703                         if(!m_prop.physical)
1704                                 pos_translator.update(m_position, is_end_position, update_interval);
1705                 } else {
1706                         pos_translator.init(m_position);
1707                 }
1708                 rot_translator.update(m_rotation, false, update_interval);
1709                 updateNodePos();
1710         } else if (cmd == AO_CMD_SET_TEXTURE_MOD) {
1711                 std::string mod = deSerializeString16(is);
1712
1713                 // immediately reset a engine issued texture modifier if a mod sends a different one
1714                 if (m_reset_textures_timer > 0) {
1715                         m_reset_textures_timer = -1;
1716                         updateTextures(m_previous_texture_modifier);
1717                 }
1718                 updateTextures(mod);
1719         } else if (cmd == AO_CMD_SET_SPRITE) {
1720                 v2s16 p = readV2S16(is);
1721                 int num_frames = readU16(is);
1722                 float framelength = readF32(is);
1723                 bool select_horiz_by_yawpitch = readU8(is);
1724
1725                 m_tx_basepos = p;
1726                 m_anim_num_frames = num_frames;
1727                 m_anim_framelength = framelength;
1728                 m_tx_select_horiz_by_yawpitch = select_horiz_by_yawpitch;
1729
1730                 updateTexturePos();
1731         } else if (cmd == AO_CMD_SET_PHYSICS_OVERRIDE) {
1732                 float override_speed = readF32(is);
1733                 float override_jump = readF32(is);
1734                 float override_gravity = readF32(is);
1735                 // these are sent inverted so we get true when the server sends nothing
1736                 bool sneak = !readU8(is);
1737                 bool sneak_glitch = !readU8(is);
1738                 bool new_move = !readU8(is);
1739
1740
1741                 if(m_is_local_player)
1742                 {
1743                         LocalPlayer *player = m_env->getLocalPlayer();
1744                         player->physics_override_speed = override_speed;
1745                         player->physics_override_jump = override_jump;
1746                         player->physics_override_gravity = override_gravity;
1747                         player->physics_override_sneak = sneak;
1748                         player->physics_override_sneak_glitch = sneak_glitch;
1749                         player->physics_override_new_move = new_move;
1750                 }
1751         } else if (cmd == AO_CMD_SET_ANIMATION) {
1752                 // TODO: change frames send as v2s32 value
1753                 v2f range = readV2F32(is);
1754                 if (!m_is_local_player) {
1755                         m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1756                         m_animation_speed = readF32(is);
1757                         m_animation_blend = readF32(is);
1758                         // these are sent inverted so we get true when the server sends nothing
1759                         m_animation_loop = !readU8(is);
1760                         updateAnimation();
1761                 } else {
1762                         LocalPlayer *player = m_env->getLocalPlayer();
1763                         if(player->last_animation == NO_ANIM)
1764                         {
1765                                 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1766                                 m_animation_speed = readF32(is);
1767                                 m_animation_blend = readF32(is);
1768                                 // these are sent inverted so we get true when the server sends nothing
1769                                 m_animation_loop = !readU8(is);
1770                         }
1771                         // update animation only if local animations present
1772                         // and received animation is unknown (except idle animation)
1773                         bool is_known = false;
1774                         for (int i = 1;i<4;i++)
1775                         {
1776                                 if(m_animation_range.Y == player->local_animations[i].Y)
1777                                         is_known = true;
1778                         }
1779                         if(!is_known ||
1780                                         (player->local_animations[1].Y + player->local_animations[2].Y < 1))
1781                         {
1782                                         updateAnimation();
1783                         }
1784                 }
1785         } else if (cmd == AO_CMD_SET_ANIMATION_SPEED) {
1786                 m_animation_speed = readF32(is);
1787                 updateAnimationSpeed();
1788         } else if (cmd == AO_CMD_SET_BONE_POSITION) {
1789                 std::string bone = deSerializeString16(is);
1790                 v3f position = readV3F32(is);
1791                 v3f rotation = readV3F32(is);
1792                 m_bone_position[bone] = core::vector2d<v3f>(position, rotation);
1793
1794                 // updateBonePosition(); now called every step
1795         } else if (cmd == AO_CMD_ATTACH_TO) {
1796                 u16 parent_id = readS16(is);
1797                 std::string bone = deSerializeString16(is);
1798                 v3f position = readV3F32(is);
1799                 v3f rotation = readV3F32(is);
1800                 bool force_visible = readU8(is); // Returns false for EOF
1801
1802                 setAttachment(parent_id, bone, position, rotation, force_visible);
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         const bool hidden = m_client->getCamera()->getCameraMode() == CAMERA_MODE_FIRST;
1922
1923         if (m_meshnode && m_prop.visual == "upright_sprite") {
1924                 u32 buffers = m_meshnode->getMesh()->getMeshBufferCount();
1925                 for (u32 i = 0; i < buffers; i++) {
1926                         video::SMaterial &mat = m_meshnode->getMesh()->getMeshBuffer(i)->getMaterial();
1927                         // upright sprite has no backface culling
1928                         mat.setFlag(video::EMF_FRONT_FACE_CULLING, hidden);
1929                 }
1930                 return;
1931         }
1932
1933         irr::scene::ISceneNode *node = getSceneNode();
1934         if (!node)
1935                 return;
1936
1937         if (hidden) {
1938                 // Hide the mesh by culling both front and
1939                 // back faces. Serious hackyness but it works for our
1940                 // purposes. This also preserves the skeletal armature.
1941                 node->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
1942                         true);
1943                 node->setMaterialFlag(video::EMF_FRONT_FACE_CULLING,
1944                         true);
1945         } else {
1946                 // Restore mesh visibility.
1947                 node->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
1948                         m_prop.backface_culling);
1949                 node->setMaterialFlag(video::EMF_FRONT_FACE_CULLING,
1950                         false);
1951         }
1952 }
1953
1954 // Prototype
1955 GenericCAO proto_GenericCAO(NULL, NULL);