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