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