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