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