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