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