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