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