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