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