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