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