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