5702a73b617060fc9db0055d7e12e9a08e2268df
[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
42 class Settings;
43 struct ToolCapabilities;
44
45 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
46
47 core::map<u16, ClientActiveObject::Factory> ClientActiveObject::m_types;
48
49 /*
50         SmoothTranslator
51 */
52
53 struct SmoothTranslator
54 {
55         v3f vect_old;
56         v3f vect_show;
57         v3f vect_aim;
58         f32 anim_counter;
59         f32 anim_time;
60         f32 anim_time_counter;
61         bool aim_is_end;
62
63         SmoothTranslator():
64                 vect_old(0,0,0),
65                 vect_show(0,0,0),
66                 vect_aim(0,0,0),
67                 anim_counter(0),
68                 anim_time(0),
69                 anim_time_counter(0),
70                 aim_is_end(true)
71         {}
72
73         void init(v3f vect)
74         {
75                 vect_old = vect;
76                 vect_show = vect;
77                 vect_aim = vect;
78                 anim_counter = 0;
79                 anim_time = 0;
80                 anim_time_counter = 0;
81                 aim_is_end = true;
82         }
83
84         void sharpen()
85         {
86                 init(vect_show);
87         }
88
89         void update(v3f vect_new, bool is_end_position=false, float update_interval=-1)
90         {
91                 aim_is_end = is_end_position;
92                 vect_old = vect_show;
93                 vect_aim = vect_new;
94                 if(update_interval > 0){
95                         anim_time = update_interval;
96                 } else {
97                         if(anim_time < 0.001 || anim_time > 1.0)
98                                 anim_time = anim_time_counter;
99                         else
100                                 anim_time = anim_time * 0.9 + anim_time_counter * 0.1;
101                 }
102                 anim_time_counter = 0;
103                 anim_counter = 0;
104         }
105
106         void translate(f32 dtime)
107         {
108                 anim_time_counter = anim_time_counter + dtime;
109                 anim_counter = anim_counter + dtime;
110                 v3f vect_move = vect_aim - vect_old;
111                 f32 moveratio = 1.0;
112                 if(anim_time > 0.001)
113                         moveratio = anim_time_counter / anim_time;
114                 // Move a bit less than should, to avoid oscillation
115                 moveratio = moveratio * 0.8;
116                 float move_end = 1.5;
117                 if(aim_is_end)
118                         move_end = 1.0;
119                 if(moveratio > move_end)
120                         moveratio = move_end;
121                 vect_show = vect_old + vect_move * moveratio;
122         }
123
124         bool is_moving()
125         {
126                 return ((anim_time_counter / anim_time) < 1.4);
127         }
128 };
129
130 /*
131         Other stuff
132 */
133
134 static void setBillboardTextureMatrix(scene::IBillboardSceneNode *bill,
135                 float txs, float tys, int col, int row)
136 {
137         video::SMaterial& material = bill->getMaterial(0);
138         core::matrix4& matrix = material.getTextureMatrix(0);
139         matrix.setTextureTranslate(txs*col, tys*row);
140         matrix.setTextureScale(txs, tys);
141 }
142
143 /*
144         TestCAO
145 */
146
147 class TestCAO : public ClientActiveObject
148 {
149 public:
150         TestCAO(IGameDef *gamedef, ClientEnvironment *env);
151         virtual ~TestCAO();
152         
153         u8 getType() const
154         {
155                 return ACTIVEOBJECT_TYPE_TEST;
156         }
157         
158         static ClientActiveObject* create(IGameDef *gamedef, ClientEnvironment *env);
159
160         void addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc,
161                         IrrlichtDevice *irr);
162         void removeFromScene();
163         void updateLight(u8 light_at_pos);
164         v3s16 getLightPosition();
165         void updateNodePos();
166
167         void step(float dtime, ClientEnvironment *env);
168
169         void processMessage(const std::string &data);
170
171 private:
172         scene::IMeshSceneNode *m_node;
173         v3f m_position;
174 };
175
176 // Prototype
177 TestCAO proto_TestCAO(NULL, NULL);
178
179 TestCAO::TestCAO(IGameDef *gamedef, ClientEnvironment *env):
180         ClientActiveObject(0, gamedef, env),
181         m_node(NULL),
182         m_position(v3f(0,10*BS,0))
183 {
184         ClientActiveObject::registerType(getType(), create);
185 }
186
187 TestCAO::~TestCAO()
188 {
189 }
190
191 ClientActiveObject* TestCAO::create(IGameDef *gamedef, ClientEnvironment *env)
192 {
193         return new TestCAO(gamedef, env);
194 }
195
196 void TestCAO::addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc,
197                         IrrlichtDevice *irr)
198 {
199         if(m_node != NULL)
200                 return;
201         
202         //video::IVideoDriver* driver = smgr->getVideoDriver();
203         
204         scene::SMesh *mesh = new scene::SMesh();
205         scene::IMeshBuffer *buf = new scene::SMeshBuffer();
206         video::SColor c(255,255,255,255);
207         video::S3DVertex vertices[4] =
208         {
209                 video::S3DVertex(-BS/2,-BS/4,0, 0,0,0, c, 0,1),
210                 video::S3DVertex(BS/2,-BS/4,0, 0,0,0, c, 1,1),
211                 video::S3DVertex(BS/2,BS/4,0, 0,0,0, c, 1,0),
212                 video::S3DVertex(-BS/2,BS/4,0, 0,0,0, c, 0,0),
213         };
214         u16 indices[] = {0,1,2,2,3,0};
215         buf->append(vertices, 4, indices, 6);
216         // Set material
217         buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
218         buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
219         buf->getMaterial().setTexture(0, tsrc->getTextureRaw("rat.png"));
220         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
221         buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
222         buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
223         // Add to mesh
224         mesh->addMeshBuffer(buf);
225         buf->drop();
226         m_node = smgr->addMeshSceneNode(mesh, NULL);
227         mesh->drop();
228         updateNodePos();
229 }
230
231 void TestCAO::removeFromScene()
232 {
233         if(m_node == NULL)
234                 return;
235
236         m_node->remove();
237         m_node = NULL;
238 }
239
240 void TestCAO::updateLight(u8 light_at_pos)
241 {
242 }
243
244 v3s16 TestCAO::getLightPosition()
245 {
246         return floatToInt(m_position, BS);
247 }
248
249 void TestCAO::updateNodePos()
250 {
251         if(m_node == NULL)
252                 return;
253
254         m_node->setPosition(m_position);
255         //m_node->setRotation(v3f(0, 45, 0));
256 }
257
258 void TestCAO::step(float dtime, ClientEnvironment *env)
259 {
260         if(m_node)
261         {
262                 v3f rot = m_node->getRotation();
263                 //infostream<<"dtime="<<dtime<<", rot.Y="<<rot.Y<<std::endl;
264                 rot.Y += dtime * 180;
265                 m_node->setRotation(rot);
266         }
267 }
268
269 void TestCAO::processMessage(const std::string &data)
270 {
271         infostream<<"TestCAO: Got data: "<<data<<std::endl;
272         std::istringstream is(data, std::ios::binary);
273         u16 cmd;
274         is>>cmd;
275         if(cmd == 0)
276         {
277                 v3f newpos;
278                 is>>newpos.X;
279                 is>>newpos.Y;
280                 is>>newpos.Z;
281                 m_position = newpos;
282                 updateNodePos();
283         }
284 }
285
286 /*
287         ItemCAO
288 */
289
290 class ItemCAO : public ClientActiveObject
291 {
292 public:
293         ItemCAO(IGameDef *gamedef, ClientEnvironment *env);
294         virtual ~ItemCAO();
295         
296         u8 getType() const
297         {
298                 return ACTIVEOBJECT_TYPE_ITEM;
299         }
300         
301         static ClientActiveObject* create(IGameDef *gamedef, ClientEnvironment *env);
302
303         void addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc,
304                         IrrlichtDevice *irr);
305         void removeFromScene();
306         void updateLight(u8 light_at_pos);
307         v3s16 getLightPosition();
308         void updateNodePos();
309         void updateInfoText();
310         void updateTexture();
311
312         void step(float dtime, ClientEnvironment *env);
313
314         void processMessage(const std::string &data);
315
316         void initialize(const std::string &data);
317         
318         core::aabbox3d<f32>* getSelectionBox()
319                 {return &m_selection_box;}
320         v3f getPosition()
321                 {return m_position;}
322         
323         std::string infoText()
324                 {return m_infotext;}
325
326 private:
327         core::aabbox3d<f32> m_selection_box;
328         scene::IMeshSceneNode *m_node;
329         v3f m_position;
330         std::string m_itemstring;
331         std::string m_infotext;
332 };
333
334 #include "inventory.h"
335
336 // Prototype
337 ItemCAO proto_ItemCAO(NULL, NULL);
338
339 ItemCAO::ItemCAO(IGameDef *gamedef, ClientEnvironment *env):
340         ClientActiveObject(0, gamedef, env),
341         m_selection_box(-BS/3.,0.0,-BS/3., BS/3.,BS*2./3.,BS/3.),
342         m_node(NULL),
343         m_position(v3f(0,10*BS,0))
344 {
345         if(!gamedef && !env)
346         {
347                 ClientActiveObject::registerType(getType(), create);
348         }
349 }
350
351 ItemCAO::~ItemCAO()
352 {
353 }
354
355 ClientActiveObject* ItemCAO::create(IGameDef *gamedef, ClientEnvironment *env)
356 {
357         return new ItemCAO(gamedef, env);
358 }
359
360 void ItemCAO::addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc,
361                         IrrlichtDevice *irr)
362 {
363         if(m_node != NULL)
364                 return;
365         
366         //video::IVideoDriver* driver = smgr->getVideoDriver();
367         
368         scene::SMesh *mesh = new scene::SMesh();
369         scene::IMeshBuffer *buf = new scene::SMeshBuffer();
370         video::SColor c(255,255,255,255);
371         video::S3DVertex vertices[4] =
372         {
373                 /*video::S3DVertex(-BS/2,-BS/4,0, 0,0,0, c, 0,1),
374                 video::S3DVertex(BS/2,-BS/4,0, 0,0,0, c, 1,1),
375                 video::S3DVertex(BS/2,BS/4,0, 0,0,0, c, 1,0),
376                 video::S3DVertex(-BS/2,BS/4,0, 0,0,0, c, 0,0),*/
377                 video::S3DVertex(BS/3.,0,0, 0,0,0, c, 0,1),
378                 video::S3DVertex(-BS/3.,0,0, 0,0,0, c, 1,1),
379                 video::S3DVertex(-BS/3.,0+BS*2./3.,0, 0,0,0, c, 1,0),
380                 video::S3DVertex(BS/3.,0+BS*2./3.,0, 0,0,0, c, 0,0),
381         };
382         u16 indices[] = {0,1,2,2,3,0};
383         buf->append(vertices, 4, indices, 6);
384         // Set material
385         buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
386         buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
387         // Initialize with a generated placeholder texture
388         buf->getMaterial().setTexture(0, tsrc->getTextureRaw(""));
389         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
390         buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
391         buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
392         // Add to mesh
393         mesh->addMeshBuffer(buf);
394         buf->drop();
395         m_node = smgr->addMeshSceneNode(mesh, NULL);
396         mesh->drop();
397         updateNodePos();
398
399         /*
400                 Update image of node
401         */
402
403         updateTexture();
404 }
405
406 void ItemCAO::removeFromScene()
407 {
408         if(m_node == NULL)
409                 return;
410
411         m_node->remove();
412         m_node = NULL;
413 }
414
415 void ItemCAO::updateLight(u8 light_at_pos)
416 {
417         if(m_node == NULL)
418                 return;
419
420         u8 li = decode_light(light_at_pos);
421         video::SColor color(255,li,li,li);
422         setMeshColor(m_node->getMesh(), color);
423 }
424
425 v3s16 ItemCAO::getLightPosition()
426 {
427         return floatToInt(m_position + v3f(0,0.5*BS,0), BS);
428 }
429
430 void ItemCAO::updateNodePos()
431 {
432         if(m_node == NULL)
433                 return;
434
435         m_node->setPosition(m_position);
436 }
437
438 void ItemCAO::updateInfoText()
439 {
440         try{
441                 IItemDefManager *idef = m_gamedef->idef();
442                 ItemStack item;
443                 item.deSerialize(m_itemstring, idef);
444                 if(item.isKnown(idef))
445                         m_infotext = item.getDefinition(idef).description;
446                 else
447                         m_infotext = "Unknown item: '" + m_itemstring + "'";
448                 if(item.count >= 2)
449                         m_infotext += " (" + itos(item.count) + ")";
450         }
451         catch(SerializationError &e)
452         {
453                 m_infotext = "Unknown item: '" + m_itemstring + "'";
454         }
455 }
456
457 void ItemCAO::updateTexture()
458 {
459         if(m_node == NULL)
460                 return;
461
462         // Create an inventory item to see what is its image
463         std::istringstream is(m_itemstring, std::ios_base::binary);
464         video::ITexture *texture = NULL;
465         try{
466                 IItemDefManager *idef = m_gamedef->idef();
467                 ItemStack item;
468                 item.deSerialize(is, idef);
469                 texture = item.getDefinition(idef).inventory_texture;
470         }
471         catch(SerializationError &e)
472         {
473                 infostream<<"WARNING: "<<__FUNCTION_NAME
474                                 <<": error deSerializing itemstring \""
475                                 <<m_itemstring<<std::endl;
476         }
477         
478         // Set meshbuffer texture
479         m_node->getMaterial(0).setTexture(0, texture);
480 }
481
482
483 void ItemCAO::step(float dtime, ClientEnvironment *env)
484 {
485         if(m_node)
486         {
487                 /*v3f rot = m_node->getRotation();
488                 rot.Y += dtime * 120;
489                 m_node->setRotation(rot);*/
490                 LocalPlayer *player = env->getLocalPlayer();
491                 assert(player);
492                 v3f rot = m_node->getRotation();
493                 rot.Y = 180.0 - (player->getYaw());
494                 m_node->setRotation(rot);
495         }
496 }
497
498 void ItemCAO::processMessage(const std::string &data)
499 {
500         //infostream<<"ItemCAO: Got message"<<std::endl;
501         std::istringstream is(data, std::ios::binary);
502         // command
503         u8 cmd = readU8(is);
504         if(cmd == 0)
505         {
506                 // pos
507                 m_position = readV3F1000(is);
508                 updateNodePos();
509         }
510         if(cmd == 1)
511         {
512                 // itemstring
513                 m_itemstring = deSerializeString(is);
514                 updateInfoText();
515                 updateTexture();
516         }
517 }
518
519 void ItemCAO::initialize(const std::string &data)
520 {
521         infostream<<"ItemCAO: Got init data"<<std::endl;
522         
523         {
524                 std::istringstream is(data, std::ios::binary);
525                 // version
526                 u8 version = readU8(is);
527                 // check version
528                 if(version != 0)
529                         return;
530                 // pos
531                 m_position = readV3F1000(is);
532                 // itemstring
533                 m_itemstring = deSerializeString(is);
534         }
535         
536         updateNodePos();
537         updateInfoText();
538 }
539
540 /*
541         GenericCAO
542 */
543
544 #include "genericobject.h"
545
546 class GenericCAO : public ClientActiveObject
547 {
548 private:
549         // Only set at initialization
550         std::string m_name;
551         bool m_is_player;
552         bool m_is_local_player; // determined locally
553         // Property-ish things
554         ObjectProperties m_prop;
555         //
556         scene::ISceneManager *m_smgr;
557         IrrlichtDevice *m_irr;
558         core::aabbox3d<f32> m_selection_box;
559         scene::IMeshSceneNode *m_meshnode;
560         scene::IBillboardSceneNode *m_spritenode;
561         scene::ITextSceneNode* m_textnode;
562         v3f m_position;
563         v3f m_velocity;
564         v3f m_acceleration;
565         float m_yaw;
566         s16 m_hp;
567         SmoothTranslator pos_translator;
568         // Spritesheet/animation stuff
569         v2f m_tx_size;
570         v2s16 m_tx_basepos;
571         bool m_initial_tx_basepos_set;
572         bool m_tx_select_horiz_by_yawpitch;
573         int m_anim_frame;
574         int m_anim_num_frames;
575         float m_anim_framelength;
576         float m_anim_timer;
577         ItemGroupList m_armor_groups;
578         float m_reset_textures_timer;
579         bool m_visuals_expired;
580         float m_step_distance_counter;
581         u8 m_last_light;
582
583 public:
584         GenericCAO(IGameDef *gamedef, ClientEnvironment *env):
585                 ClientActiveObject(0, gamedef, env),
586                 //
587                 m_is_player(false),
588                 m_is_local_player(false),
589                 //
590                 m_smgr(NULL),
591                 m_irr(NULL),
592                 m_selection_box(-BS/3.,-BS/3.,-BS/3., BS/3.,BS/3.,BS/3.),
593                 m_meshnode(NULL),
594                 m_spritenode(NULL),
595                 m_textnode(NULL),
596                 m_position(v3f(0,10*BS,0)),
597                 m_velocity(v3f(0,0,0)),
598                 m_acceleration(v3f(0,0,0)),
599                 m_yaw(0),
600                 m_hp(1),
601                 m_tx_size(1,1),
602                 m_tx_basepos(0,0),
603                 m_initial_tx_basepos_set(false),
604                 m_tx_select_horiz_by_yawpitch(false),
605                 m_anim_frame(0),
606                 m_anim_num_frames(1),
607                 m_anim_framelength(0.2),
608                 m_anim_timer(0),
609                 m_reset_textures_timer(-1),
610                 m_visuals_expired(false),
611                 m_step_distance_counter(0),
612                 m_last_light(255)
613         {
614                 if(gamedef == NULL)
615                         ClientActiveObject::registerType(getType(), create);
616         }
617
618         void initialize(const std::string &data)
619         {
620                 infostream<<"GenericCAO: Got init data"<<std::endl;
621                 std::istringstream is(data, std::ios::binary);
622                 // version
623                 u8 version = readU8(is);
624                 // check version
625                 if(version != 0){
626                         errorstream<<"GenericCAO: Unsupported init data version"
627                                         <<std::endl;
628                         return;
629                 }
630                 m_name = deSerializeString(is);
631                 m_is_player = readU8(is);
632                 m_position = readV3F1000(is);
633                 m_yaw = readF1000(is);
634                 m_hp = readS16(is);
635                 
636                 int num_messages = readU8(is);
637                 for(int i=0; i<num_messages; i++){
638                         std::string message = deSerializeLongString(is);
639                         processMessage(message);
640                 }
641
642                 pos_translator.init(m_position);
643                 updateNodePos();
644                 
645                 if(m_is_player){
646                         Player *player = m_env->getPlayer(m_name.c_str());
647                         if(player && player->isLocal()){
648                                 m_is_local_player = true;
649                         }
650                 }
651         }
652
653         ~GenericCAO()
654         {
655         }
656
657         static ClientActiveObject* create(IGameDef *gamedef, ClientEnvironment *env)
658         {
659                 return new GenericCAO(gamedef, env);
660         }
661
662         u8 getType() const
663         {
664                 return ACTIVEOBJECT_TYPE_GENERIC;
665         }
666         core::aabbox3d<f32>* getSelectionBox()
667         {
668                 if(!m_prop.is_visible || m_is_local_player)
669                         return NULL;
670                 return &m_selection_box;
671         }
672         v3f getPosition()
673         {
674                 return pos_translator.vect_show;
675         }
676
677         void removeFromScene()
678         {
679                 if(m_meshnode){
680                         m_meshnode->remove();
681                         m_meshnode = NULL;
682                 }
683                 if(m_spritenode){
684                         m_spritenode->remove();
685                         m_spritenode = NULL;
686                 }
687         }
688
689         void addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc,
690                         IrrlichtDevice *irr)
691         {
692                 m_smgr = smgr;
693                 m_irr = irr;
694
695                 if(m_meshnode != NULL || m_spritenode != NULL)
696                         return;
697                 
698                 m_visuals_expired = false;
699
700                 if(!m_prop.is_visible || m_is_local_player)
701                         return;
702         
703                 //video::IVideoDriver* driver = smgr->getVideoDriver();
704
705                 if(m_prop.visual == "sprite"){
706                         infostream<<"GenericCAO::addToScene(): single_sprite"<<std::endl;
707                         m_spritenode = smgr->addBillboardSceneNode(
708                                         NULL, v2f(1, 1), v3f(0,0,0), -1);
709                         m_spritenode->setMaterialTexture(0,
710                                         tsrc->getTextureRaw("unknown_block.png"));
711                         m_spritenode->setMaterialFlag(video::EMF_LIGHTING, false);
712                         m_spritenode->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
713                         m_spritenode->setMaterialType(video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF);
714                         m_spritenode->setMaterialFlag(video::EMF_FOG_ENABLE, true);
715                         u8 li = m_last_light;
716                         m_spritenode->setColor(video::SColor(255,li,li,li));
717                         m_spritenode->setSize(m_prop.visual_size*BS);
718                         {
719                                 const float txs = 1.0 / 1;
720                                 const float tys = 1.0 / 1;
721                                 setBillboardTextureMatrix(m_spritenode,
722                                                 txs, tys, 0, 0);
723                         }
724                 }
725                 else if(m_prop.visual == "upright_sprite")
726                 {
727                         scene::SMesh *mesh = new scene::SMesh();
728                         double dx = BS*m_prop.visual_size.X/2;
729                         double dy = BS*m_prop.visual_size.Y/2;
730                         { // Front
731                         scene::IMeshBuffer *buf = new scene::SMeshBuffer();
732                         u8 li = m_last_light;
733                         video::SColor c(255,li,li,li);
734                         video::S3DVertex vertices[4] =
735                         {
736                                 video::S3DVertex(-dx,-dy,0, 0,0,0, c, 0,1),
737                                 video::S3DVertex(dx,-dy,0, 0,0,0, c, 1,1),
738                                 video::S3DVertex(dx,dy,0, 0,0,0, c, 1,0),
739                                 video::S3DVertex(-dx,dy,0, 0,0,0, c, 0,0),
740                         };
741                         u16 indices[] = {0,1,2,2,3,0};
742                         buf->append(vertices, 4, indices, 6);
743                         // Set material
744                         buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
745                         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
746                         buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
747                         buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
748                         // Add to mesh
749                         mesh->addMeshBuffer(buf);
750                         buf->drop();
751                         }
752                         { // Back
753                         scene::IMeshBuffer *buf = new scene::SMeshBuffer();
754                         u8 li = m_last_light;
755                         video::SColor c(255,li,li,li);
756                         video::S3DVertex vertices[4] =
757                         {
758                                 video::S3DVertex(dx,-dy,0, 0,0,0, c, 1,1),
759                                 video::S3DVertex(-dx,-dy,0, 0,0,0, c, 0,1),
760                                 video::S3DVertex(-dx,dy,0, 0,0,0, c, 0,0),
761                                 video::S3DVertex(dx,dy,0, 0,0,0, c, 1,0),
762                         };
763                         u16 indices[] = {0,1,2,2,3,0};
764                         buf->append(vertices, 4, indices, 6);
765                         // Set material
766                         buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
767                         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
768                         buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
769                         buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
770                         // Add to mesh
771                         mesh->addMeshBuffer(buf);
772                         buf->drop();
773                         }
774                         m_meshnode = smgr->addMeshSceneNode(mesh, NULL);
775                         mesh->drop();
776                         // Set it to use the materials of the meshbuffers directly.
777                         // This is needed for changing the texture in the future
778                         m_meshnode->setReadOnlyMaterials(true);
779                 }
780                 else if(m_prop.visual == "cube"){
781                         infostream<<"GenericCAO::addToScene(): cube"<<std::endl;
782                         scene::IMesh *mesh = createCubeMesh(v3f(BS,BS,BS));
783                         m_meshnode = smgr->addMeshSceneNode(mesh, NULL);
784                         mesh->drop();
785                         
786                         m_meshnode->setScale(v3f(m_prop.visual_size.X,
787                                         m_prop.visual_size.Y,
788                                         m_prop.visual_size.X));
789                         u8 li = m_last_light;
790                         setMeshColor(m_meshnode->getMesh(), video::SColor(255,li,li,li));
791                 } else if(m_prop.visual == "wielditem"){
792                         infostream<<"GenericCAO::addToScene(): node"<<std::endl;
793                         infostream<<"textures: "<<m_prop.textures.size()<<std::endl;
794                         if(m_prop.textures.size() >= 1){
795                                 infostream<<"textures[0]: "<<m_prop.textures[0]<<std::endl;
796                                 IItemDefManager *idef = m_gamedef->idef();
797                                 ItemStack item(m_prop.textures[0], 1, 0, "", idef);
798                                 scene::IMesh *mesh = item.getDefinition(idef).wield_mesh;
799                                 m_meshnode = smgr->addMeshSceneNode(mesh, NULL);
800                                 
801                                 m_meshnode->setScale(v3f(m_prop.visual_size.X/2,
802                                                 m_prop.visual_size.Y/2,
803                                                 m_prop.visual_size.X/2));
804                                 u8 li = m_last_light;
805                                 setMeshColor(m_meshnode->getMesh(), video::SColor(255,li,li,li));
806                         }
807                 } else {
808                         infostream<<"GenericCAO::addToScene(): \""<<m_prop.visual
809                                         <<"\" not supported"<<std::endl;
810                 }
811                 updateTextures("");
812                 
813                 scene::ISceneNode *node = NULL;
814                 if(m_spritenode)
815                         node = m_spritenode;
816                 else if(m_meshnode)
817                         node = m_meshnode;
818                 if(node && m_is_player && !m_is_local_player){
819                         // Add a text node for showing the name
820                         gui::IGUIEnvironment* gui = irr->getGUIEnvironment();
821                         std::wstring wname = narrow_to_wide(m_name);
822                         m_textnode = smgr->addTextSceneNode(gui->getBuiltInFont(),
823                                         wname.c_str(), video::SColor(255,255,255,255), node);
824                         m_textnode->setPosition(v3f(0, BS*1.1, 0));
825                 }
826                 
827                 updateNodePos();
828         }
829
830         void expireVisuals()
831         {
832                 m_visuals_expired = true;
833         }
834                 
835         void updateLight(u8 light_at_pos)
836         {
837                 bool is_visible = (m_hp != 0);
838                 u8 li = decode_light(light_at_pos);
839                 m_last_light = li;
840                 video::SColor color(255,li,li,li);
841                 if(m_meshnode){
842                         setMeshColor(m_meshnode->getMesh(), color);
843                         m_meshnode->setVisible(is_visible);
844                 }
845                 if(m_spritenode){
846                         m_spritenode->setColor(color);
847                         m_spritenode->setVisible(is_visible);
848                 }
849         }
850
851         v3s16 getLightPosition()
852         {
853                 return floatToInt(m_position, BS);
854         }
855
856         void updateNodePos()
857         {
858                 if(m_meshnode){
859                         m_meshnode->setPosition(pos_translator.vect_show);
860                         v3f rot = m_meshnode->getRotation();
861                         rot.Y = -m_yaw;
862                         m_meshnode->setRotation(rot);
863                 }
864                 if(m_spritenode){
865                         m_spritenode->setPosition(pos_translator.vect_show);
866                 }
867         }
868
869         void step(float dtime, ClientEnvironment *env)
870         {
871                 v3f lastpos = pos_translator.vect_show;
872
873                 if(m_visuals_expired && m_smgr && m_irr){
874                         m_visuals_expired = false;
875                         removeFromScene();
876                         addToScene(m_smgr, m_gamedef->tsrc(), m_irr);
877                 }
878
879                 if(m_prop.physical){
880                         core::aabbox3d<f32> box = m_prop.collisionbox;
881                         box.MinEdge *= BS;
882                         box.MaxEdge *= BS;
883                         collisionMoveResult moveresult;
884                         f32 pos_max_d = BS*0.125; // Distance per iteration
885                         f32 stepheight = 0;
886                         v3f p_pos = m_position;
887                         v3f p_velocity = m_velocity;
888                         v3f p_acceleration = m_acceleration;
889                         IGameDef *gamedef = env->getGameDef();
890                         moveresult = collisionMoveSimple(&env->getMap(), gamedef,
891                                         pos_max_d, box, stepheight, dtime,
892                                         p_pos, p_velocity, p_acceleration);
893                         // Apply results
894                         m_position = p_pos;
895                         m_velocity = p_velocity;
896                         m_acceleration = p_acceleration;
897                         
898                         bool is_end_position = moveresult.collides;
899                         pos_translator.update(m_position, is_end_position, dtime);
900                         pos_translator.translate(dtime);
901                         updateNodePos();
902                 } else {
903                         m_position += dtime * m_velocity + 0.5 * dtime * dtime * m_acceleration;
904                         m_velocity += dtime * m_acceleration;
905                         pos_translator.update(m_position, pos_translator.aim_is_end, pos_translator.anim_time);
906                         pos_translator.translate(dtime);
907                         updateNodePos();
908                 }
909
910                 float moved = lastpos.getDistanceFrom(pos_translator.vect_show);
911                 m_step_distance_counter += moved;
912                 if(m_step_distance_counter > 1.5*BS){
913                         m_step_distance_counter = 0;
914                         if(!m_is_local_player && m_prop.makes_footstep_sound){
915                                 INodeDefManager *ndef = m_gamedef->ndef();
916                                 v3s16 p = floatToInt(getPosition() + v3f(0,
917                                                 (m_prop.collisionbox.MinEdge.Y-0.5)*BS, 0), BS);
918                                 MapNode n = m_env->getMap().getNodeNoEx(p);
919                                 SimpleSoundSpec spec = ndef->get(n).sound_footstep;
920                                 m_gamedef->sound()->playSoundAt(spec, false, getPosition());
921                         }
922                 }
923
924                 m_anim_timer += dtime;
925                 if(m_anim_timer >= m_anim_framelength){
926                         m_anim_timer -= m_anim_framelength;
927                         m_anim_frame++;
928                         if(m_anim_frame >= m_anim_num_frames)
929                                 m_anim_frame = 0;
930                 }
931
932                 updateTexturePos();
933
934                 if(m_reset_textures_timer >= 0){
935                         m_reset_textures_timer -= dtime;
936                         if(m_reset_textures_timer <= 0){
937                                 m_reset_textures_timer = -1;
938                                 updateTextures("");
939                         }
940                 }
941                 if(fabs(m_prop.automatic_rotate) > 0.001){
942                         m_yaw += dtime * m_prop.automatic_rotate * 180 / M_PI;
943                         updateNodePos();
944                 }
945         }
946
947         void updateTexturePos()
948         {
949                 if(m_spritenode){
950                         scene::ICameraSceneNode* camera =
951                                         m_spritenode->getSceneManager()->getActiveCamera();
952                         if(!camera)
953                                 return;
954                         v3f cam_to_entity = m_spritenode->getAbsolutePosition()
955                                         - camera->getAbsolutePosition();
956                         cam_to_entity.normalize();
957
958                         int row = m_tx_basepos.Y;
959                         int col = m_tx_basepos.X;
960                         
961                         if(m_tx_select_horiz_by_yawpitch)
962                         {
963                                 if(cam_to_entity.Y > 0.75)
964                                         col += 5;
965                                 else if(cam_to_entity.Y < -0.75)
966                                         col += 4;
967                                 else{
968                                         float mob_dir = atan2(cam_to_entity.Z, cam_to_entity.X) / M_PI * 180.;
969                                         float dir = mob_dir - m_yaw;
970                                         dir = wrapDegrees_180(dir);
971                                         //infostream<<"id="<<m_id<<" dir="<<dir<<std::endl;
972                                         if(fabs(wrapDegrees_180(dir - 0)) <= 45.1)
973                                                 col += 2;
974                                         else if(fabs(wrapDegrees_180(dir - 90)) <= 45.1)
975                                                 col += 3;
976                                         else if(fabs(wrapDegrees_180(dir - 180)) <= 45.1)
977                                                 col += 0;
978                                         else if(fabs(wrapDegrees_180(dir + 90)) <= 45.1)
979                                                 col += 1;
980                                         else
981                                                 col += 4;
982                                 }
983                         }
984                         
985                         // Animation goes downwards
986                         row += m_anim_frame;
987
988                         float txs = m_tx_size.X;
989                         float tys = m_tx_size.Y;
990                         setBillboardTextureMatrix(m_spritenode,
991                                         txs, tys, col, row);
992                 }
993         }
994
995         void updateTextures(const std::string &mod)
996         {
997                 ITextureSource *tsrc = m_gamedef->tsrc();
998
999                 if(m_spritenode)
1000                 {
1001                         if(m_prop.visual == "sprite")
1002                         {
1003                                 std::string texturestring = "unknown_block.png";
1004                                 if(m_prop.textures.size() >= 1)
1005                                         texturestring = m_prop.textures[0];
1006                                 texturestring += mod;
1007                                 m_spritenode->setMaterialTexture(0,
1008                                                 tsrc->getTextureRaw(texturestring));
1009                         }
1010                 }
1011                 if(m_meshnode)
1012                 {
1013                         if(m_prop.visual == "cube")
1014                         {
1015                                 for (u32 i = 0; i < 6; ++i)
1016                                 {
1017                                         std::string texturestring = "unknown_block.png";
1018                                         if(m_prop.textures.size() > i)
1019                                                 texturestring = m_prop.textures[i];
1020                                         texturestring += mod;
1021                                         AtlasPointer ap = tsrc->getTexture(texturestring);
1022
1023                                         // Get the tile texture and atlas transformation
1024                                         video::ITexture* atlas = ap.atlas;
1025                                         v2f pos = ap.pos;
1026                                         v2f size = ap.size;
1027
1028                                         // Set material flags and texture
1029                                         video::SMaterial& material = m_meshnode->getMaterial(i);
1030                                         material.setFlag(video::EMF_LIGHTING, false);
1031                                         material.setFlag(video::EMF_BILINEAR_FILTER, false);
1032                                         material.setTexture(0, atlas);
1033                                         material.getTextureMatrix(0).setTextureTranslate(pos.X, pos.Y);
1034                                         material.getTextureMatrix(0).setTextureScale(size.X, size.Y);
1035                                 }
1036                         }
1037                         else if(m_prop.visual == "upright_sprite")
1038                         {
1039                                 scene::IMesh *mesh = m_meshnode->getMesh();
1040                                 {
1041                                         std::string tname = "unknown_object.png";
1042                                         if(m_prop.textures.size() >= 1)
1043                                                 tname = m_prop.textures[0];
1044                                         tname += mod;
1045                                         scene::IMeshBuffer *buf = mesh->getMeshBuffer(0);
1046                                         buf->getMaterial().setTexture(0,
1047                                                         tsrc->getTextureRaw(tname));
1048                                 }
1049                                 {
1050                                         std::string tname = "unknown_object.png";
1051                                         if(m_prop.textures.size() >= 2)
1052                                                 tname = m_prop.textures[1];
1053                                         else if(m_prop.textures.size() >= 1)
1054                                                 tname = m_prop.textures[0];
1055                                         tname += mod;
1056                                         scene::IMeshBuffer *buf = mesh->getMeshBuffer(1);
1057                                         buf->getMaterial().setTexture(0,
1058                                                         tsrc->getTextureRaw(tname));
1059                                 }
1060                         }
1061                 }
1062         }
1063
1064         void processMessage(const std::string &data)
1065         {
1066                 //infostream<<"GenericCAO: Got message"<<std::endl;
1067                 std::istringstream is(data, std::ios::binary);
1068                 // command
1069                 u8 cmd = readU8(is);
1070                 if(cmd == GENERIC_CMD_SET_PROPERTIES)
1071                 {
1072                         m_prop = gob_read_set_properties(is);
1073
1074                         m_selection_box = m_prop.collisionbox;
1075                         m_selection_box.MinEdge *= BS;
1076                         m_selection_box.MaxEdge *= BS;
1077                                 
1078                         m_tx_size.X = 1.0 / m_prop.spritediv.X;
1079                         m_tx_size.Y = 1.0 / m_prop.spritediv.Y;
1080
1081                         if(!m_initial_tx_basepos_set){
1082                                 m_initial_tx_basepos_set = true;
1083                                 m_tx_basepos = m_prop.initial_sprite_basepos;
1084                         }
1085                         
1086                         expireVisuals();
1087                 }
1088                 else if(cmd == GENERIC_CMD_UPDATE_POSITION)
1089                 {
1090                         m_position = readV3F1000(is);
1091                         m_velocity = readV3F1000(is);
1092                         m_acceleration = readV3F1000(is);
1093                         if(fabs(m_prop.automatic_rotate) < 0.001)
1094                                 m_yaw = readF1000(is);
1095                         bool do_interpolate = readU8(is);
1096                         bool is_end_position = readU8(is);
1097                         float update_interval = readF1000(is);
1098
1099                         // Place us a bit higher if we're physical, to not sink into
1100                         // the ground due to sucky collision detection...
1101                         if(m_prop.physical)
1102                                 m_position += v3f(0,0.002,0);
1103                         
1104                         if(do_interpolate){
1105                                 if(!m_prop.physical)
1106                                         pos_translator.update(m_position, is_end_position, update_interval);
1107                         } else {
1108                                 pos_translator.init(m_position);
1109                         }
1110                         updateNodePos();
1111                 }
1112                 else if(cmd == GENERIC_CMD_SET_TEXTURE_MOD)
1113                 {
1114                         std::string mod = deSerializeString(is);
1115                         updateTextures(mod);
1116                 }
1117                 else if(cmd == GENERIC_CMD_SET_SPRITE)
1118                 {
1119                         v2s16 p = readV2S16(is);
1120                         int num_frames = readU16(is);
1121                         float framelength = readF1000(is);
1122                         bool select_horiz_by_yawpitch = readU8(is);
1123                         
1124                         m_tx_basepos = p;
1125                         m_anim_num_frames = num_frames;
1126                         m_anim_framelength = framelength;
1127                         m_tx_select_horiz_by_yawpitch = select_horiz_by_yawpitch;
1128
1129                         updateTexturePos();
1130                 }
1131                 else if(cmd == GENERIC_CMD_PUNCHED)
1132                 {
1133                         /*s16 damage =*/ readS16(is);
1134                         s16 result_hp = readS16(is);
1135                         
1136                         m_hp = result_hp;
1137                 }
1138                 else if(cmd == GENERIC_CMD_UPDATE_ARMOR_GROUPS)
1139                 {
1140                         m_armor_groups.clear();
1141                         int armor_groups_size = readU16(is);
1142                         for(int i=0; i<armor_groups_size; i++){
1143                                 std::string name = deSerializeString(is);
1144                                 int rating = readS16(is);
1145                                 m_armor_groups[name] = rating;
1146                         }
1147                 }
1148         }
1149         
1150         bool directReportPunch(v3f dir, const ItemStack *punchitem=NULL,
1151                         float time_from_last_punch=1000000)
1152         {
1153                 assert(punchitem);
1154                 const ToolCapabilities *toolcap =
1155                                 &punchitem->getToolCapabilities(m_gamedef->idef());
1156                 PunchDamageResult result = getPunchDamage(
1157                                 m_armor_groups,
1158                                 toolcap,
1159                                 punchitem,
1160                                 time_from_last_punch);
1161
1162                 if(result.did_punch && result.damage != 0)
1163                 {
1164                         if(result.damage < m_hp){
1165                                 m_hp -= result.damage;
1166                         } else {
1167                                 m_hp = 0;
1168                                 // TODO: Execute defined fast response
1169                                 // As there is no definition, make a smoke puff
1170                                 ClientSimpleObject *simple = createSmokePuff(
1171                                                 m_smgr, m_env, m_position,
1172                                                 m_prop.visual_size * BS);
1173                                 m_env->addSimpleObject(simple);
1174                         }
1175                         // TODO: Execute defined fast response
1176                         // Flashing shall suffice as there is no definition
1177                         m_reset_textures_timer = 0.05;
1178                         if(result.damage >= 2)
1179                                 m_reset_textures_timer += 0.05 * result.damage;
1180                         updateTextures("^[brighten");
1181                 }
1182                 
1183                 return false;
1184         }
1185         
1186         std::string debugInfoText()
1187         {
1188                 std::ostringstream os(std::ios::binary);
1189                 os<<"GenericCAO hp="<<m_hp<<"\n";
1190                 os<<"armor={";
1191                 for(ItemGroupList::const_iterator i = m_armor_groups.begin();
1192                                 i != m_armor_groups.end(); i++){
1193                         os<<i->first<<"="<<i->second<<", ";
1194                 }
1195                 os<<"}";
1196                 return os.str();
1197         }
1198 };
1199
1200 // Prototype
1201 GenericCAO proto_GenericCAO(NULL, NULL);
1202
1203