]> git.lizzy.rs Git - minetest.git/blob - src/content_sao.cpp
Create node metadata when placing nodes again
[minetest.git] / src / content_sao.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 General Public License as published by
7 the Free Software Foundation; either version 2 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 General Public License for more details.
14
15 You should have received a copy of the GNU 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_sao.h"
21 #include "collision.h"
22 #include "environment.h"
23 #include "settings.h"
24 #include "main.h" // For g_profiler
25 #include "profiler.h"
26 #include "serialization.h" // For compressZlib
27 #include "materials.h" // For MaterialProperties and ToolDiggingProperties
28 #include "gamedef.h"
29
30 core::map<u16, ServerActiveObject::Factory> ServerActiveObject::m_types;
31
32 /* Some helper functions */
33
34 // Y is copied, X and Z change is limited
35 void accelerate_xz(v3f &speed, v3f target_speed, f32 max_increase)
36 {
37         v3f d_wanted = target_speed - speed;
38         d_wanted.Y = 0;
39         f32 dl_wanted = d_wanted.getLength();
40         f32 dl = dl_wanted;
41         if(dl > max_increase)
42                 dl = max_increase;
43         
44         v3f d = d_wanted.normalize() * dl;
45
46         speed.X += d.X;
47         speed.Z += d.Z;
48         speed.Y = target_speed.Y;
49 }
50
51 /*
52         TestSAO
53 */
54
55 // Prototype
56 TestSAO proto_TestSAO(NULL, v3f(0,0,0));
57
58 TestSAO::TestSAO(ServerEnvironment *env, v3f pos):
59         ServerActiveObject(env, pos),
60         m_timer1(0),
61         m_age(0)
62 {
63         ServerActiveObject::registerType(getType(), create);
64 }
65
66 ServerActiveObject* TestSAO::create(ServerEnvironment *env, v3f pos,
67                 const std::string &data)
68 {
69         return new TestSAO(env, pos);
70 }
71
72 void TestSAO::step(float dtime, bool send_recommended)
73 {
74         m_age += dtime;
75         if(m_age > 10)
76         {
77                 m_removed = true;
78                 return;
79         }
80
81         m_base_position.Y += dtime * BS * 2;
82         if(m_base_position.Y > 8*BS)
83                 m_base_position.Y = 2*BS;
84
85         if(send_recommended == false)
86                 return;
87
88         m_timer1 -= dtime;
89         if(m_timer1 < 0.0)
90         {
91                 m_timer1 += 0.125;
92
93                 std::string data;
94
95                 data += itos(0); // 0 = position
96                 data += " ";
97                 data += itos(m_base_position.X);
98                 data += " ";
99                 data += itos(m_base_position.Y);
100                 data += " ";
101                 data += itos(m_base_position.Z);
102
103                 ActiveObjectMessage aom(getId(), false, data);
104                 m_messages_out.push_back(aom);
105         }
106 }
107
108
109 /*
110         ItemSAO
111 */
112
113 // Prototype
114 ItemSAO proto_ItemSAO(NULL, v3f(0,0,0), "");
115
116 ItemSAO::ItemSAO(ServerEnvironment *env, v3f pos,
117                 const std::string itemstring):
118         ServerActiveObject(env, pos),
119         m_itemstring(itemstring),
120         m_itemstring_changed(false),
121         m_speed_f(0,0,0),
122         m_last_sent_position(0,0,0)
123 {
124         ServerActiveObject::registerType(getType(), create);
125 }
126
127 ServerActiveObject* ItemSAO::create(ServerEnvironment *env, v3f pos,
128                 const std::string &data)
129 {
130         std::istringstream is(data, std::ios::binary);
131         char buf[1];
132         // read version
133         is.read(buf, 1);
134         u8 version = buf[0];
135         // check if version is supported
136         if(version != 0)
137                 return NULL;
138         std::string itemstring = deSerializeString(is);
139         infostream<<"ItemSAO::create(): Creating item \""
140                         <<itemstring<<"\""<<std::endl;
141         return new ItemSAO(env, pos, itemstring);
142 }
143
144 void ItemSAO::step(float dtime, bool send_recommended)
145 {
146         ScopeProfiler sp2(g_profiler, "ItemSAO::step avg", SPT_AVG);
147
148         assert(m_env);
149
150         const float interval = 0.2;
151         if(m_move_interval.step(dtime, interval)==false)
152                 return;
153         dtime = interval;
154         
155         core::aabbox3d<f32> box(-BS/3.,0.0,-BS/3., BS/3.,BS*2./3.,BS/3.);
156         collisionMoveResult moveresult;
157         // Apply gravity
158         m_speed_f += v3f(0, -dtime*9.81*BS, 0);
159         // Maximum movement without glitches
160         f32 pos_max_d = BS*0.25;
161         // Limit speed
162         if(m_speed_f.getLength()*dtime > pos_max_d)
163                 m_speed_f *= pos_max_d / (m_speed_f.getLength()*dtime);
164         v3f pos_f = getBasePosition();
165         v3f pos_f_old = pos_f;
166         IGameDef *gamedef = m_env->getGameDef();
167         moveresult = collisionMoveSimple(&m_env->getMap(), gamedef,
168                         pos_max_d, box, dtime, pos_f, m_speed_f);
169         
170         if(send_recommended == false)
171                 return;
172
173         if(pos_f.getDistanceFrom(m_last_sent_position) > 0.05*BS)
174         {
175                 setBasePosition(pos_f);
176                 m_last_sent_position = pos_f;
177
178                 std::ostringstream os(std::ios::binary);
179                 // command (0 = update position)
180                 writeU8(os, 0);
181                 // pos
182                 writeV3F1000(os, m_base_position);
183                 // create message and add to list
184                 ActiveObjectMessage aom(getId(), false, os.str());
185                 m_messages_out.push_back(aom);
186         }
187         if(m_itemstring_changed)
188         {
189                 m_itemstring_changed = false;
190
191                 std::ostringstream os(std::ios::binary);
192                 // command (1 = update itemstring)
193                 writeU8(os, 1);
194                 // itemstring
195                 os<<serializeString(m_itemstring);
196                 // create message and add to list
197                 ActiveObjectMessage aom(getId(), false, os.str());
198                 m_messages_out.push_back(aom);
199         }
200 }
201
202 std::string ItemSAO::getClientInitializationData()
203 {
204         std::ostringstream os(std::ios::binary);
205         // version
206         writeU8(os, 0);
207         // pos
208         writeV3F1000(os, m_base_position);
209         // itemstring
210         os<<serializeString(m_itemstring);
211         return os.str();
212 }
213
214 std::string ItemSAO::getStaticData()
215 {
216         infostream<<__FUNCTION_NAME<<std::endl;
217         std::ostringstream os(std::ios::binary);
218         // version
219         writeU8(os, 0);
220         // itemstring
221         os<<serializeString(m_itemstring);
222         return os.str();
223 }
224
225 ItemStack ItemSAO::createItemStack()
226 {
227         try{
228                 IItemDefManager *idef = m_env->getGameDef()->idef();
229                 ItemStack item;
230                 item.deSerialize(m_itemstring, idef);
231                 infostream<<__FUNCTION_NAME<<": m_itemstring=\""<<m_itemstring
232                                 <<"\" -> item=\""<<item.getItemString()<<"\""
233                                 <<std::endl;
234                 return item;
235         }
236         catch(SerializationError &e)
237         {
238                 infostream<<__FUNCTION_NAME<<": serialization error: "
239                                 <<"m_itemstring=\""<<m_itemstring<<"\""<<std::endl;
240                 return ItemStack();
241         }
242 }
243
244 void ItemSAO::punch(ServerActiveObject *puncher, float time_from_last_punch)
245 {
246         // Allow removing items in creative mode
247         if(g_settings->getBool("creative_mode") == true)
248         {
249                 m_removed = true;
250                 return;
251         }
252
253         ItemStack item = createItemStack();
254         Inventory *inv = puncher->getInventory();
255         if(inv != NULL)
256         {
257                 std::string wieldlist = puncher->getWieldList();
258                 ItemStack leftover = inv->addItem(wieldlist, item);
259                 puncher->setInventoryModified();
260                 if(leftover.empty())
261                 {
262                         m_removed = true;
263                 }
264                 else
265                 {
266                         m_itemstring = leftover.getItemString();
267                         m_itemstring_changed = true;
268                 }
269         }
270 }
271
272 /*
273         RatSAO
274 */
275
276 // Prototype
277 RatSAO proto_RatSAO(NULL, v3f(0,0,0));
278
279 RatSAO::RatSAO(ServerEnvironment *env, v3f pos):
280         ServerActiveObject(env, pos),
281         m_is_active(false),
282         m_speed_f(0,0,0)
283 {
284         ServerActiveObject::registerType(getType(), create);
285
286         m_oldpos = v3f(0,0,0);
287         m_last_sent_position = v3f(0,0,0);
288         m_yaw = myrand_range(0,PI*2);
289         m_counter1 = 0;
290         m_counter2 = 0;
291         m_age = 0;
292         m_touching_ground = false;
293 }
294
295 ServerActiveObject* RatSAO::create(ServerEnvironment *env, v3f pos,
296                 const std::string &data)
297 {
298         std::istringstream is(data, std::ios::binary);
299         char buf[1];
300         // read version
301         is.read(buf, 1);
302         u8 version = buf[0];
303         // check if version is supported
304         if(version != 0)
305                 return NULL;
306         return new RatSAO(env, pos);
307 }
308
309 void RatSAO::step(float dtime, bool send_recommended)
310 {
311         ScopeProfiler sp2(g_profiler, "RatSAO::step avg", SPT_AVG);
312
313         assert(m_env);
314
315         if(m_is_active == false)
316         {
317                 if(m_inactive_interval.step(dtime, 0.5)==false)
318                         return;
319         }
320
321         /*
322                 The AI
323         */
324
325         /*m_age += dtime;
326         if(m_age > 60)
327         {
328                 // Die
329                 m_removed = true;
330                 return;
331         }*/
332
333         // Apply gravity
334         m_speed_f.Y -= dtime*9.81*BS;
335
336         /*
337                 Move around if some player is close
338         */
339         bool player_is_close = false;
340         // Check connected players
341         core::list<Player*> players = m_env->getPlayers(true);
342         core::list<Player*>::Iterator i;
343         for(i = players.begin();
344                         i != players.end(); i++)
345         {
346                 Player *player = *i;
347                 v3f playerpos = player->getPosition();
348                 if(m_base_position.getDistanceFrom(playerpos) < BS*10.0)
349                 {
350                         player_is_close = true;
351                         break;
352                 }
353         }
354
355         m_is_active = player_is_close;
356         
357         if(player_is_close == false)
358         {
359                 m_speed_f.X = 0;
360                 m_speed_f.Z = 0;
361         }
362         else
363         {
364                 // Move around
365                 v3f dir(cos(m_yaw/180*PI),0,sin(m_yaw/180*PI));
366                 f32 speed = 2*BS;
367                 m_speed_f.X = speed * dir.X;
368                 m_speed_f.Z = speed * dir.Z;
369
370                 if(m_touching_ground && (m_oldpos - m_base_position).getLength()
371                                 < dtime*speed/2)
372                 {
373                         m_counter1 -= dtime;
374                         if(m_counter1 < 0.0)
375                         {
376                                 m_counter1 += 1.0;
377                                 m_speed_f.Y = 5.0*BS;
378                         }
379                 }
380
381                 {
382                         m_counter2 -= dtime;
383                         if(m_counter2 < 0.0)
384                         {
385                                 m_counter2 += (float)(myrand()%100)/100*3.0;
386                                 m_yaw += ((float)(myrand()%200)-100)/100*180;
387                                 m_yaw = wrapDegrees(m_yaw);
388                         }
389                 }
390         }
391         
392         m_oldpos = m_base_position;
393
394         /*
395                 Move it, with collision detection
396         */
397
398         core::aabbox3d<f32> box(-BS/3.,0.0,-BS/3., BS/3.,BS*2./3.,BS/3.);
399         collisionMoveResult moveresult;
400         // Maximum movement without glitches
401         f32 pos_max_d = BS*0.25;
402         // Limit speed
403         if(m_speed_f.getLength()*dtime > pos_max_d)
404                 m_speed_f *= pos_max_d / (m_speed_f.getLength()*dtime);
405         v3f pos_f = getBasePosition();
406         v3f pos_f_old = pos_f;
407         IGameDef *gamedef = m_env->getGameDef();
408         moveresult = collisionMoveSimple(&m_env->getMap(), gamedef,
409                         pos_max_d, box, dtime, pos_f, m_speed_f);
410         m_touching_ground = moveresult.touching_ground;
411         
412         setBasePosition(pos_f);
413
414         if(send_recommended == false)
415                 return;
416
417         if(pos_f.getDistanceFrom(m_last_sent_position) > 0.05*BS)
418         {
419                 m_last_sent_position = pos_f;
420
421                 std::ostringstream os(std::ios::binary);
422                 // command (0 = update position)
423                 writeU8(os, 0);
424                 // pos
425                 writeV3F1000(os, m_base_position);
426                 // yaw
427                 writeF1000(os, m_yaw);
428                 // create message and add to list
429                 ActiveObjectMessage aom(getId(), false, os.str());
430                 m_messages_out.push_back(aom);
431         }
432 }
433
434 std::string RatSAO::getClientInitializationData()
435 {
436         std::ostringstream os(std::ios::binary);
437         // version
438         writeU8(os, 0);
439         // pos
440         writeV3F1000(os, m_base_position);
441         return os.str();
442 }
443
444 std::string RatSAO::getStaticData()
445 {
446         //infostream<<__FUNCTION_NAME<<std::endl;
447         std::ostringstream os(std::ios::binary);
448         // version
449         writeU8(os, 0);
450         return os.str();
451 }
452
453 void RatSAO::punch(ServerActiveObject *puncher, float time_from_last_punch)
454 {
455         // Allow removing rats in creative mode
456         if(g_settings->getBool("creative_mode") == true)
457         {
458                 m_removed = true;
459                 return;
460         }
461
462         IItemDefManager *idef = m_env->getGameDef()->idef();
463         ItemStack item("rat", 1, 0, "", idef);
464         Inventory *inv = puncher->getInventory();
465         if(inv != NULL)
466         {
467                 std::string wieldlist = puncher->getWieldList();
468                 ItemStack leftover = inv->addItem(wieldlist, item);
469                 puncher->setInventoryModified();
470                 if(leftover.empty())
471                         m_removed = true;
472         }
473 }
474
475 /*
476         Oerkki1SAO
477 */
478
479 // Prototype
480 Oerkki1SAO proto_Oerkki1SAO(NULL, v3f(0,0,0));
481
482 Oerkki1SAO::Oerkki1SAO(ServerEnvironment *env, v3f pos):
483         ServerActiveObject(env, pos),
484         m_is_active(false),
485         m_speed_f(0,0,0)
486 {
487         ServerActiveObject::registerType(getType(), create);
488
489         m_oldpos = v3f(0,0,0);
490         m_last_sent_position = v3f(0,0,0);
491         m_yaw = 0;
492         m_counter1 = 0;
493         m_counter2 = 0;
494         m_age = 0;
495         m_touching_ground = false;
496         m_hp = 20;
497         m_after_jump_timer = 0;
498 }
499
500 ServerActiveObject* Oerkki1SAO::create(ServerEnvironment *env, v3f pos,
501                 const std::string &data)
502 {
503         std::istringstream is(data, std::ios::binary);
504         // read version
505         u8 version = readU8(is);
506         // read hp
507         u8 hp = readU8(is);
508         // check if version is supported
509         if(version != 0)
510                 return NULL;
511         Oerkki1SAO *o = new Oerkki1SAO(env, pos);
512         o->m_hp = hp;
513         return o;
514 }
515
516 void Oerkki1SAO::step(float dtime, bool send_recommended)
517 {
518         ScopeProfiler sp2(g_profiler, "Oerkki1SAO::step avg", SPT_AVG);
519
520         assert(m_env);
521
522         if(m_is_active == false)
523         {
524                 if(m_inactive_interval.step(dtime, 0.5)==false)
525                         return;
526         }
527
528         /*
529                 The AI
530         */
531
532         m_age += dtime;
533         if(m_age > 120)
534         {
535                 // Die
536                 m_removed = true;
537                 return;
538         }
539
540         m_after_jump_timer -= dtime;
541
542         v3f old_speed = m_speed_f;
543
544         // Apply gravity
545         m_speed_f.Y -= dtime*9.81*BS;
546
547         /*
548                 Move around if some player is close
549         */
550         bool player_is_close = false;
551         bool player_is_too_close = false;
552         v3f near_player_pos;
553         // Check connected players
554         core::list<Player*> players = m_env->getPlayers(true);
555         core::list<Player*>::Iterator i;
556         for(i = players.begin();
557                         i != players.end(); i++)
558         {
559                 Player *player = *i;
560                 v3f playerpos = player->getPosition();
561                 f32 dist = m_base_position.getDistanceFrom(playerpos);
562                 if(dist < BS*0.6)
563                 {
564                         m_removed = true;
565                         return;
566                         player_is_too_close = true;
567                         near_player_pos = playerpos;
568                 }
569                 else if(dist < BS*15.0 && !player_is_too_close)
570                 {
571                         player_is_close = true;
572                         near_player_pos = playerpos;
573                 }
574         }
575
576         m_is_active = player_is_close;
577
578         v3f target_speed = m_speed_f;
579
580         if(!player_is_close)
581         {
582                 target_speed = v3f(0,0,0);
583         }
584         else
585         {
586                 // Move around
587
588                 v3f ndir = near_player_pos - m_base_position;
589                 ndir.Y = 0;
590                 ndir.normalize();
591
592                 f32 nyaw = 180./PI*atan2(ndir.Z,ndir.X);
593                 if(nyaw < m_yaw - 180)
594                         nyaw += 360;
595                 else if(nyaw > m_yaw + 180)
596                         nyaw -= 360;
597                 m_yaw = 0.95*m_yaw + 0.05*nyaw;
598                 m_yaw = wrapDegrees(m_yaw);
599                 
600                 f32 speed = 2*BS;
601
602                 if((m_touching_ground || m_after_jump_timer > 0.0)
603                                 && !player_is_too_close)
604                 {
605                         v3f dir(cos(m_yaw/180*PI),0,sin(m_yaw/180*PI));
606                         target_speed.X = speed * dir.X;
607                         target_speed.Z = speed * dir.Z;
608                 }
609
610                 if(m_touching_ground && (m_oldpos - m_base_position).getLength()
611                                 < dtime*speed/2)
612                 {
613                         m_counter1 -= dtime;
614                         if(m_counter1 < 0.0)
615                         {
616                                 m_counter1 += 0.2;
617                                 // Jump
618                                 target_speed.Y = 5.0*BS;
619                                 m_after_jump_timer = 1.0;
620                         }
621                 }
622
623                 {
624                         m_counter2 -= dtime;
625                         if(m_counter2 < 0.0)
626                         {
627                                 m_counter2 += (float)(myrand()%100)/100*3.0;
628                                 //m_yaw += ((float)(myrand()%200)-100)/100*180;
629                                 m_yaw += ((float)(myrand()%200)-100)/100*90;
630                                 m_yaw = wrapDegrees(m_yaw);
631                         }
632                 }
633         }
634         
635         if((m_speed_f - target_speed).getLength() > BS*4 || player_is_too_close)
636                 accelerate_xz(m_speed_f, target_speed, dtime*BS*8);
637         else
638                 accelerate_xz(m_speed_f, target_speed, dtime*BS*4);
639         
640         m_oldpos = m_base_position;
641
642         /*
643                 Move it, with collision detection
644         */
645
646         core::aabbox3d<f32> box(-BS/3.,0.0,-BS/3., BS/3.,BS*5./3.,BS/3.);
647         collisionMoveResult moveresult;
648         // Maximum movement without glitches
649         f32 pos_max_d = BS*0.25;
650         /*// Limit speed
651         if(m_speed_f.getLength()*dtime > pos_max_d)
652                 m_speed_f *= pos_max_d / (m_speed_f.getLength()*dtime);*/
653         v3f pos_f = getBasePosition();
654         v3f pos_f_old = pos_f;
655         IGameDef *gamedef = m_env->getGameDef();
656         moveresult = collisionMovePrecise(&m_env->getMap(), gamedef,
657                         pos_max_d, box, dtime, pos_f, m_speed_f);
658         m_touching_ground = moveresult.touching_ground;
659         
660         // Do collision damage
661         float tolerance = BS*30;
662         float factor = BS*0.5;
663         v3f speed_diff = old_speed - m_speed_f;
664         // Increase effect in X and Z
665         speed_diff.X *= 2;
666         speed_diff.Z *= 2;
667         float vel = speed_diff.getLength();
668         if(vel > tolerance)
669         {
670                 f32 damage_f = (vel - tolerance)/BS*factor;
671                 u16 damage = (u16)(damage_f+0.5);
672                 doDamage(damage);
673         }
674
675         setBasePosition(pos_f);
676
677         if(send_recommended == false && m_speed_f.getLength() < 3.0*BS)
678                 return;
679
680         if(pos_f.getDistanceFrom(m_last_sent_position) > 0.05*BS)
681         {
682                 m_last_sent_position = pos_f;
683
684                 std::ostringstream os(std::ios::binary);
685                 // command (0 = update position)
686                 writeU8(os, 0);
687                 // pos
688                 writeV3F1000(os, m_base_position);
689                 // yaw
690                 writeF1000(os, m_yaw);
691                 // create message and add to list
692                 ActiveObjectMessage aom(getId(), false, os.str());
693                 m_messages_out.push_back(aom);
694         }
695 }
696
697 std::string Oerkki1SAO::getClientInitializationData()
698 {
699         std::ostringstream os(std::ios::binary);
700         // version
701         writeU8(os, 0);
702         // pos
703         writeV3F1000(os, m_base_position);
704         return os.str();
705 }
706
707 std::string Oerkki1SAO::getStaticData()
708 {
709         //infostream<<__FUNCTION_NAME<<std::endl;
710         std::ostringstream os(std::ios::binary);
711         // version
712         writeU8(os, 0);
713         // hp
714         writeU8(os, m_hp);
715         return os.str();
716 }
717
718 void Oerkki1SAO::punch(ServerActiveObject *puncher, float time_from_last_punch)
719 {
720         if(!puncher)
721                 return;
722         
723         v3f dir = (getBasePosition() - puncher->getBasePosition()).normalize();
724         m_speed_f += dir*12*BS;
725
726         // "Material" properties of an oerkki
727         MaterialProperties mp;
728         mp.diggability = DIGGABLE_NORMAL;
729         mp.crackiness = -1.0;
730         mp.cuttability = 1.0;
731
732         IItemDefManager *idef = m_env->getGameDef()->idef();
733         ItemStack punchitem = puncher->getWieldedItem();
734         ToolDiggingProperties tp =
735                         punchitem.getToolDiggingProperties(idef);
736
737         HittingProperties hitprop = getHittingProperties(&mp, &tp,
738                         time_from_last_punch);
739
740         doDamage(hitprop.hp);
741         if(g_settings->getBool("creative_mode") == false)
742         {
743                 punchitem.addWear(hitprop.wear, idef);
744                 puncher->setWieldedItem(punchitem);
745         }
746 }
747
748 void Oerkki1SAO::doDamage(u16 d)
749 {
750         infostream<<"oerkki damage: "<<d<<std::endl;
751         
752         if(d < m_hp)
753         {
754                 m_hp -= d;
755         }
756         else
757         {
758                 // Die
759                 m_hp = 0;
760                 m_removed = true;
761         }
762
763         {
764                 std::ostringstream os(std::ios::binary);
765                 // command (1 = damage)
766                 writeU8(os, 1);
767                 // amount
768                 writeU8(os, d);
769                 // create message and add to list
770                 ActiveObjectMessage aom(getId(), false, os.str());
771                 m_messages_out.push_back(aom);
772         }
773 }
774
775 /*
776         FireflySAO
777 */
778
779 // Prototype
780 FireflySAO proto_FireflySAO(NULL, v3f(0,0,0));
781
782 FireflySAO::FireflySAO(ServerEnvironment *env, v3f pos):
783         ServerActiveObject(env, pos),
784         m_is_active(false),
785         m_speed_f(0,0,0)
786 {
787         ServerActiveObject::registerType(getType(), create);
788
789         m_oldpos = v3f(0,0,0);
790         m_last_sent_position = v3f(0,0,0);
791         m_yaw = 0;
792         m_counter1 = 0;
793         m_counter2 = 0;
794         m_age = 0;
795         m_touching_ground = false;
796 }
797
798 ServerActiveObject* FireflySAO::create(ServerEnvironment *env, v3f pos,
799                 const std::string &data)
800 {
801         std::istringstream is(data, std::ios::binary);
802         char buf[1];
803         // read version
804         is.read(buf, 1);
805         u8 version = buf[0];
806         // check if version is supported
807         if(version != 0)
808                 return NULL;
809         return new FireflySAO(env, pos);
810 }
811
812 void FireflySAO::step(float dtime, bool send_recommended)
813 {
814         ScopeProfiler sp2(g_profiler, "FireflySAO::step avg", SPT_AVG);
815
816         assert(m_env);
817
818         if(m_is_active == false)
819         {
820                 if(m_inactive_interval.step(dtime, 0.5)==false)
821                         return;
822         }
823
824         /*
825                 The AI
826         */
827
828         // Apply (less) gravity
829         m_speed_f.Y -= dtime*3*BS;
830
831         /*
832                 Move around if some player is close
833         */
834         bool player_is_close = false;
835         // Check connected players
836         core::list<Player*> players = m_env->getPlayers(true);
837         core::list<Player*>::Iterator i;
838         for(i = players.begin();
839                         i != players.end(); i++)
840         {
841                 Player *player = *i;
842                 v3f playerpos = player->getPosition();
843                 if(m_base_position.getDistanceFrom(playerpos) < BS*10.0)
844                 {
845                         player_is_close = true;
846                         break;
847                 }
848         }
849
850         m_is_active = player_is_close;
851         
852         if(player_is_close == false)
853         {
854                 m_speed_f.X = 0;
855                 m_speed_f.Z = 0;
856         }
857         else
858         {
859                 // Move around
860                 v3f dir(cos(m_yaw/180*PI),0,sin(m_yaw/180*PI));
861                 f32 speed = BS/2;
862                 m_speed_f.X = speed * dir.X;
863                 m_speed_f.Z = speed * dir.Z;
864
865                 if(m_touching_ground && (m_oldpos - m_base_position).getLength()
866                                 < dtime*speed/2)
867                 {
868                         m_counter1 -= dtime;
869                         if(m_counter1 < 0.0)
870                         {
871                                 m_counter1 += 1.0;
872                                 m_speed_f.Y = 5.0*BS;
873                         }
874                 }
875
876                 {
877                         m_counter2 -= dtime;
878                         if(m_counter2 < 0.0)
879                         {
880                                 m_counter2 += (float)(myrand()%100)/100*3.0;
881                                 m_yaw += ((float)(myrand()%200)-100)/100*180;
882                                 m_yaw = wrapDegrees(m_yaw);
883                         }
884                 }
885         }
886         
887         m_oldpos = m_base_position;
888
889         /*
890                 Move it, with collision detection
891         */
892
893         core::aabbox3d<f32> box(-BS/3.,-BS*2/3.0,-BS/3., BS/3.,BS*4./3.,BS/3.);
894         collisionMoveResult moveresult;
895         // Maximum movement without glitches
896         f32 pos_max_d = BS*0.25;
897         // Limit speed
898         if(m_speed_f.getLength()*dtime > pos_max_d)
899                 m_speed_f *= pos_max_d / (m_speed_f.getLength()*dtime);
900         v3f pos_f = getBasePosition();
901         v3f pos_f_old = pos_f;
902         IGameDef *gamedef = m_env->getGameDef();
903         moveresult = collisionMoveSimple(&m_env->getMap(), gamedef,
904                         pos_max_d, box, dtime, pos_f, m_speed_f);
905         m_touching_ground = moveresult.touching_ground;
906         
907         setBasePosition(pos_f);
908
909         if(send_recommended == false)
910                 return;
911
912         if(pos_f.getDistanceFrom(m_last_sent_position) > 0.05*BS)
913         {
914                 m_last_sent_position = pos_f;
915
916                 std::ostringstream os(std::ios::binary);
917                 // command (0 = update position)
918                 writeU8(os, 0);
919                 // pos
920                 writeV3F1000(os, m_base_position);
921                 // yaw
922                 writeF1000(os, m_yaw);
923                 // create message and add to list
924                 ActiveObjectMessage aom(getId(), false, os.str());
925                 m_messages_out.push_back(aom);
926         }
927 }
928
929 std::string FireflySAO::getClientInitializationData()
930 {
931         std::ostringstream os(std::ios::binary);
932         // version
933         writeU8(os, 0);
934         // pos
935         writeV3F1000(os, m_base_position);
936         return os.str();
937 }
938
939 std::string FireflySAO::getStaticData()
940 {
941         //infostream<<__FUNCTION_NAME<<std::endl;
942         std::ostringstream os(std::ios::binary);
943         // version
944         writeU8(os, 0);
945         return os.str();
946 }
947
948 /*
949         MobV2SAO
950 */
951
952 // Prototype
953 MobV2SAO proto_MobV2SAO(NULL, v3f(0,0,0), NULL);
954
955 MobV2SAO::MobV2SAO(ServerEnvironment *env, v3f pos,
956                 Settings *init_properties):
957         ServerActiveObject(env, pos),
958         m_move_type("ground_nodes"),
959         m_speed(0,0,0),
960         m_last_sent_position(0,0,0),
961         m_oldpos(0,0,0),
962         m_yaw(0),
963         m_counter1(0),
964         m_counter2(0),
965         m_age(0),
966         m_touching_ground(false),
967         m_hp(10),
968         m_walk_around(false),
969         m_walk_around_timer(0),
970         m_next_pos_exists(false),
971         m_shoot_reload_timer(0),
972         m_shooting(false),
973         m_shooting_timer(0),
974         m_falling(false),
975         m_disturb_timer(100000),
976         m_random_disturb_timer(0),
977         m_shoot_y(0)
978 {
979         ServerActiveObject::registerType(getType(), create);
980         
981         m_properties = new Settings();
982         if(init_properties)
983                 m_properties->update(*init_properties);
984         
985         m_properties->setV3F("pos", pos);
986         
987         setPropertyDefaults();
988         readProperties();
989 }
990         
991 MobV2SAO::~MobV2SAO()
992 {
993         delete m_properties;
994 }
995
996 ServerActiveObject* MobV2SAO::create(ServerEnvironment *env, v3f pos,
997                 const std::string &data)
998 {
999         std::istringstream is(data, std::ios::binary);
1000         Settings properties;
1001         properties.parseConfigLines(is, "MobArgsEnd");
1002         MobV2SAO *o = new MobV2SAO(env, pos, &properties);
1003         return o;
1004 }
1005
1006 std::string MobV2SAO::getStaticData()
1007 {
1008         updateProperties();
1009
1010         std::ostringstream os(std::ios::binary);
1011         m_properties->writeLines(os);
1012         return os.str();
1013 }
1014
1015 std::string MobV2SAO::getClientInitializationData()
1016 {
1017         //infostream<<__FUNCTION_NAME<<std::endl;
1018
1019         updateProperties();
1020
1021         std::ostringstream os(std::ios::binary);
1022
1023         // version
1024         writeU8(os, 0);
1025         
1026         Settings client_properties;
1027         
1028         /*client_properties.set("version", "0");
1029         client_properties.updateValue(*m_properties, "pos");
1030         client_properties.updateValue(*m_properties, "yaw");
1031         client_properties.updateValue(*m_properties, "hp");*/
1032
1033         // Just send everything for simplicity
1034         client_properties.update(*m_properties);
1035
1036         std::ostringstream os2(std::ios::binary);
1037         client_properties.writeLines(os2);
1038         compressZlib(os2.str(), os);
1039
1040         return os.str();
1041 }
1042
1043 bool checkFreePosition(Map *map, v3s16 p0, v3s16 size)
1044 {
1045         for(int dx=0; dx<size.X; dx++)
1046         for(int dy=0; dy<size.Y; dy++)
1047         for(int dz=0; dz<size.Z; dz++){
1048                 v3s16 dp(dx, dy, dz);
1049                 v3s16 p = p0 + dp;
1050                 MapNode n = map->getNodeNoEx(p);
1051                 if(n.getContent() != CONTENT_AIR)
1052                         return false;
1053         }
1054         return true;
1055 }
1056
1057 bool checkWalkablePosition(Map *map, v3s16 p0)
1058 {
1059         v3s16 p = p0 + v3s16(0,-1,0);
1060         MapNode n = map->getNodeNoEx(p);
1061         if(n.getContent() != CONTENT_AIR)
1062                 return true;
1063         return false;
1064 }
1065
1066 bool checkFreeAndWalkablePosition(Map *map, v3s16 p0, v3s16 size)
1067 {
1068         if(!checkFreePosition(map, p0, size))
1069                 return false;
1070         if(!checkWalkablePosition(map, p0))
1071                 return false;
1072         return true;
1073 }
1074
1075 static void get_random_u32_array(u32 a[], u32 len)
1076 {
1077         u32 i, n;
1078         for(i=0; i<len; i++)
1079                 a[i] = i;
1080         n = len;
1081         while(n > 1){
1082                 u32 k = myrand() % n;
1083                 n--;
1084                 u32 temp = a[n];
1085                 a[n] = a[k];
1086                 a[k] = temp;
1087         }
1088 }
1089
1090 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
1091
1092 static void explodeSquare(Map *map, v3s16 p0, v3s16 size)
1093 {
1094         core::map<v3s16, MapBlock*> modified_blocks;
1095
1096         for(int dx=0; dx<size.X; dx++)
1097         for(int dy=0; dy<size.Y; dy++)
1098         for(int dz=0; dz<size.Z; dz++){
1099                 v3s16 dp(dx - size.X/2, dy - size.Y/2, dz - size.Z/2);
1100                 v3s16 p = p0 + dp;
1101                 MapNode n = map->getNodeNoEx(p);
1102                 if(n.getContent() == CONTENT_IGNORE)
1103                         continue;
1104                 //map->removeNodeWithEvent(p);
1105                 map->removeNodeAndUpdate(p, modified_blocks);
1106         }
1107
1108         // Send a MEET_OTHER event
1109         MapEditEvent event;
1110         event.type = MEET_OTHER;
1111         for(core::map<v3s16, MapBlock*>::Iterator
1112                   i = modified_blocks.getIterator();
1113                   i.atEnd() == false; i++)
1114         {
1115                 v3s16 p = i.getNode()->getKey();
1116                 event.modified_blocks.insert(p, true);
1117         }
1118         map->dispatchEvent(&event);
1119 }
1120
1121 void MobV2SAO::step(float dtime, bool send_recommended)
1122 {
1123         ScopeProfiler sp2(g_profiler, "MobV2SAO::step avg", SPT_AVG);
1124
1125         assert(m_env);
1126         Map *map = &m_env->getMap();
1127
1128         m_age += dtime;
1129
1130         if(m_die_age >= 0.0 && m_age >= m_die_age){
1131                 m_removed = true;
1132                 return;
1133         }
1134
1135         m_random_disturb_timer += dtime;
1136         if(m_random_disturb_timer >= 5.0)
1137         {
1138                 m_random_disturb_timer = 0;
1139                 // Check connected players
1140                 core::list<Player*> players = m_env->getPlayers(true);
1141                 core::list<Player*>::Iterator i;
1142                 for(i = players.begin();
1143                                 i != players.end(); i++)
1144                 {
1145                         Player *player = *i;
1146                         v3f playerpos = player->getPosition();
1147                         f32 dist = m_base_position.getDistanceFrom(playerpos);
1148                         if(dist < BS*16)
1149                         {
1150                                 if(myrand_range(0,3) == 0){
1151                                         actionstream<<"Mob id="<<m_id<<" at "
1152                                                         <<PP(m_base_position/BS)
1153                                                         <<" got randomly disturbed by "
1154                                                         <<player->getName()<<std::endl;
1155                                         m_disturbing_player = player->getName();
1156                                         m_disturb_timer = 0;
1157                                         break;
1158                                 }
1159                         }
1160                 }
1161         }
1162
1163         Player *disturbing_player =
1164                         m_env->getPlayer(m_disturbing_player.c_str());
1165         v3f disturbing_player_off = v3f(0,1,0);
1166         v3f disturbing_player_norm = v3f(0,1,0);
1167         float disturbing_player_distance = 1000000;
1168         float disturbing_player_dir = 0;
1169         if(disturbing_player){
1170                 disturbing_player_off =
1171                                 disturbing_player->getPosition() - m_base_position;
1172                 disturbing_player_distance = disturbing_player_off.getLength();
1173                 disturbing_player_norm = disturbing_player_off;
1174                 disturbing_player_norm.normalize();
1175                 disturbing_player_dir = 180./PI*atan2(disturbing_player_norm.Z,
1176                                 disturbing_player_norm.X);
1177         }
1178
1179         m_disturb_timer += dtime;
1180         
1181         if(!m_falling)
1182         {
1183                 m_shooting_timer -= dtime;
1184                 if(m_shooting_timer <= 0.0 && m_shooting){
1185                         m_shooting = false;
1186                         
1187                         std::string shoot_type = m_properties->get("shoot_type");
1188                         v3f shoot_pos(0,0,0);
1189                         shoot_pos.Y += m_properties->getFloat("shoot_y") * BS;
1190                         if(shoot_type == "fireball"){
1191                                 v3f dir(cos(m_yaw/180*PI),0,sin(m_yaw/180*PI));
1192                                 dir.Y = m_shoot_y;
1193                                 dir.normalize();
1194                                 v3f speed = dir * BS * 10.0;
1195                                 v3f pos = m_base_position + shoot_pos;
1196                                 infostream<<__FUNCTION_NAME<<": Mob id="<<m_id
1197                                                 <<" shooting fireball from "<<PP(pos)
1198                                                 <<" at speed "<<PP(speed)<<std::endl;
1199                                 Settings properties;
1200                                 properties.set("looks", "fireball");
1201                                 properties.setV3F("speed", speed);
1202                                 properties.setFloat("die_age", 5.0);
1203                                 properties.set("move_type", "constant_speed");
1204                                 properties.setFloat("hp", 1000);
1205                                 properties.set("lock_full_brightness", "true");
1206                                 properties.set("player_hit_damage", "9");
1207                                 properties.set("player_hit_distance", "2");
1208                                 properties.set("player_hit_interval", "1");
1209                                 ServerActiveObject *obj = new MobV2SAO(m_env,
1210                                                 pos, &properties);
1211                                 //m_env->addActiveObjectAsStatic(obj);
1212                                 m_env->addActiveObject(obj);
1213                         } else {
1214                                 infostream<<__FUNCTION_NAME<<": Mob id="<<m_id
1215                                                 <<": Unknown shoot_type="<<shoot_type
1216                                                 <<std::endl;
1217                         }
1218                 }
1219
1220                 m_shoot_reload_timer += dtime;
1221
1222                 float reload_time = 15.0;
1223                 if(m_disturb_timer <= 15.0)
1224                         reload_time = 3.0;
1225
1226                 bool shoot_without_player = false;
1227                 if(m_properties->getBool("mindless_rage"))
1228                         shoot_without_player = true;
1229
1230                 if(!m_shooting && m_shoot_reload_timer >= reload_time &&
1231                                 !m_next_pos_exists &&
1232                                 (m_disturb_timer <= 60.0 || shoot_without_player))
1233                 {
1234                         m_shoot_y = 0;
1235                         if(m_disturb_timer < 60.0 && disturbing_player &&
1236                                         disturbing_player_distance < 16*BS &&
1237                                         fabs(disturbing_player_norm.Y) < 0.8){
1238                                 m_yaw = disturbing_player_dir;
1239                                 sendPosition();
1240                                 m_shoot_y += disturbing_player_norm.Y;
1241                         } else {
1242                                 m_shoot_y = 0.01 * myrand_range(-30,10);
1243                         }
1244                         m_shoot_reload_timer = 0.0;
1245                         m_shooting = true;
1246                         m_shooting_timer = 1.5;
1247                         {
1248                                 std::ostringstream os(std::ios::binary);
1249                                 // command (2 = shooting)
1250                                 writeU8(os, 2);
1251                                 // time
1252                                 writeF1000(os, m_shooting_timer + 0.1);
1253                                 // bright?
1254                                 writeU8(os, true);
1255                                 // create message and add to list
1256                                 ActiveObjectMessage aom(getId(), false, os.str());
1257                                 m_messages_out.push_back(aom);
1258                         }
1259                 }
1260         }
1261         
1262         if(m_move_type == "ground_nodes")
1263         {
1264                 if(!m_shooting){
1265                         m_walk_around_timer -= dtime;
1266                         if(m_walk_around_timer <= 0.0){
1267                                 m_walk_around = !m_walk_around;
1268                                 if(m_walk_around)
1269                                         m_walk_around_timer = 0.1*myrand_range(10,50);
1270                                 else
1271                                         m_walk_around_timer = 0.1*myrand_range(30,70);
1272                         }
1273                 }
1274
1275                 /* Move */
1276                 if(m_next_pos_exists){
1277                         v3f pos_f = m_base_position;
1278                         v3f next_pos_f = intToFloat(m_next_pos_i, BS);
1279
1280                         v3f v = next_pos_f - pos_f;
1281                         m_yaw = atan2(v.Z, v.X) / PI * 180;
1282                         
1283                         v3f diff = next_pos_f - pos_f;
1284                         v3f dir = diff;
1285                         dir.normalize();
1286                         float speed = BS * 0.5;
1287                         if(m_falling)
1288                                 speed = BS * 3.0;
1289                         dir *= dtime * speed;
1290                         bool arrived = false;
1291                         if(dir.getLength() > diff.getLength()){
1292                                 dir = diff;
1293                                 arrived = true;
1294                         }
1295                         pos_f += dir;
1296                         m_base_position = pos_f;
1297
1298                         if((pos_f - next_pos_f).getLength() < 0.1 || arrived){
1299                                 m_next_pos_exists = false;
1300                         }
1301                 }
1302
1303                 v3s16 pos_i = floatToInt(m_base_position, BS);
1304                 v3s16 size_blocks = v3s16(m_size.X+0.5,m_size.Y+0.5,m_size.X+0.5);
1305                 v3s16 pos_size_off(0,0,0);
1306                 if(m_size.X >= 2.5){
1307                         pos_size_off.X = -1;
1308                         pos_size_off.Y = -1;
1309                 }
1310                 
1311                 if(!m_next_pos_exists){
1312                         /* Check whether to drop down */
1313                         if(checkFreePosition(map,
1314                                         pos_i + pos_size_off + v3s16(0,-1,0), size_blocks)){
1315                                 m_next_pos_i = pos_i + v3s16(0,-1,0);
1316                                 m_next_pos_exists = true;
1317                                 m_falling = true;
1318                         } else {
1319                                 m_falling = false;
1320                         }
1321                 }
1322
1323                 if(m_walk_around)
1324                 {
1325                         if(!m_next_pos_exists){
1326                                 /* Find some position where to go next */
1327                                 v3s16 dps[3*3*3];
1328                                 int num_dps = 0;
1329                                 for(int dx=-1; dx<=1; dx++)
1330                                 for(int dy=-1; dy<=1; dy++)
1331                                 for(int dz=-1; dz<=1; dz++){
1332                                         if(dx == 0 && dy == 0)
1333                                                 continue;
1334                                         if(dx != 0 && dz != 0 && dy != 0)
1335                                                 continue;
1336                                         dps[num_dps++] = v3s16(dx,dy,dz);
1337                                 }
1338                                 u32 order[3*3*3];
1339                                 get_random_u32_array(order, num_dps);
1340                                 for(int i=0; i<num_dps; i++){
1341                                         v3s16 p = dps[order[i]] + pos_i;
1342                                         bool is_free = checkFreeAndWalkablePosition(map,
1343                                                         p + pos_size_off, size_blocks);
1344                                         if(!is_free)
1345                                                 continue;
1346                                         m_next_pos_i = p;
1347                                         m_next_pos_exists = true;
1348                                         break;
1349                                 }
1350                         }
1351                 }
1352         }
1353         else if(m_move_type == "constant_speed")
1354         {
1355                 m_base_position += m_speed * dtime;
1356                 
1357                 v3s16 pos_i = floatToInt(m_base_position, BS);
1358                 v3s16 size_blocks = v3s16(m_size.X+0.5,m_size.Y+0.5,m_size.X+0.5);
1359                 v3s16 pos_size_off(0,0,0);
1360                 if(m_size.X >= 2.5){
1361                         pos_size_off.X = -1;
1362                         pos_size_off.Y = -1;
1363                 }
1364                 bool free = checkFreePosition(map, pos_i + pos_size_off, size_blocks);
1365                 if(!free){
1366                         explodeSquare(map, pos_i, v3s16(3,3,3));
1367                         m_removed = true;
1368                         return;
1369                 }
1370         }
1371         else
1372         {
1373                 errorstream<<"MobV2SAO::step(): id="<<m_id<<" unknown move_type=\""
1374                                 <<m_move_type<<"\""<<std::endl;
1375         }
1376
1377         if(send_recommended == false)
1378                 return;
1379
1380         if(m_base_position.getDistanceFrom(m_last_sent_position) > 0.05*BS)
1381         {
1382                 sendPosition();
1383         }
1384 }
1385
1386 void MobV2SAO::punch(ServerActiveObject *puncher, float time_from_last_punch)
1387 {
1388         if(!puncher)
1389                 return;
1390         
1391         v3f dir = (getBasePosition() - puncher->getBasePosition()).normalize();
1392
1393         // A quick hack; SAO description is player name for player
1394         std::string playername = puncher->getDescription();
1395
1396         Map *map = &m_env->getMap();
1397         
1398         actionstream<<playername<<" punches mob id="<<m_id
1399                         <<" at "<<PP(m_base_position/BS)<<std::endl;
1400
1401         m_disturb_timer = 0;
1402         m_disturbing_player = playername;
1403         m_next_pos_exists = false; // Cancel moving immediately
1404         
1405         m_yaw = wrapDegrees_180(180./PI*atan2(dir.Z, dir.X) + 180.);
1406         v3f new_base_position = m_base_position + dir * BS;
1407         {
1408                 v3s16 pos_i = floatToInt(new_base_position, BS);
1409                 v3s16 size_blocks = v3s16(m_size.X+0.5,m_size.Y+0.5,m_size.X+0.5);
1410                 v3s16 pos_size_off(0,0,0);
1411                 if(m_size.X >= 2.5){
1412                         pos_size_off.X = -1;
1413                         pos_size_off.Y = -1;
1414                 }
1415                 bool free = checkFreePosition(map, pos_i + pos_size_off, size_blocks);
1416                 if(free)
1417                         m_base_position = new_base_position;
1418         }
1419         sendPosition();
1420         
1421
1422         // "Material" properties of the MobV2
1423         MaterialProperties mp;
1424         mp.diggability = DIGGABLE_NORMAL;
1425         mp.crackiness = -1.0;
1426         mp.cuttability = 1.0;
1427
1428         IItemDefManager *idef = m_env->getGameDef()->idef();
1429         ItemStack punchitem = puncher->getWieldedItem();
1430         ToolDiggingProperties tp =
1431                         punchitem.getToolDiggingProperties(idef);
1432
1433         HittingProperties hitprop = getHittingProperties(&mp, &tp,
1434                         time_from_last_punch);
1435
1436         doDamage(hitprop.hp);
1437         if(g_settings->getBool("creative_mode") == false)
1438         {
1439                 punchitem.addWear(hitprop.wear, idef);
1440                 puncher->setWieldedItem(punchitem);
1441         }
1442 }
1443
1444 bool MobV2SAO::isPeaceful()
1445 {
1446         return m_properties->getBool("is_peaceful");
1447 }
1448
1449 void MobV2SAO::sendPosition()
1450 {
1451         m_last_sent_position = m_base_position;
1452
1453         std::ostringstream os(std::ios::binary);
1454         // command (0 = update position)
1455         writeU8(os, 0);
1456         // pos
1457         writeV3F1000(os, m_base_position);
1458         // yaw
1459         writeF1000(os, m_yaw);
1460         // create message and add to list
1461         ActiveObjectMessage aom(getId(), false, os.str());
1462         m_messages_out.push_back(aom);
1463 }
1464
1465 void MobV2SAO::setPropertyDefaults()
1466 {
1467         m_properties->setDefault("is_peaceful", "false");
1468         m_properties->setDefault("move_type", "ground_nodes");
1469         m_properties->setDefault("speed", "(0,0,0)");
1470         m_properties->setDefault("age", "0");
1471         m_properties->setDefault("yaw", "0");
1472         m_properties->setDefault("pos", "(0,0,0)");
1473         m_properties->setDefault("hp", "0");
1474         m_properties->setDefault("die_age", "-1");
1475         m_properties->setDefault("size", "(1,2)");
1476         m_properties->setDefault("shoot_type", "fireball");
1477         m_properties->setDefault("shoot_y", "0");
1478         m_properties->setDefault("mindless_rage", "false");
1479 }
1480 void MobV2SAO::readProperties()
1481 {
1482         m_move_type = m_properties->get("move_type");
1483         m_speed = m_properties->getV3F("speed");
1484         m_age = m_properties->getFloat("age");
1485         m_yaw = m_properties->getFloat("yaw");
1486         m_base_position = m_properties->getV3F("pos");
1487         m_hp = m_properties->getS32("hp");
1488         m_die_age = m_properties->getFloat("die_age");
1489         m_size = m_properties->getV2F("size");
1490 }
1491 void MobV2SAO::updateProperties()
1492 {
1493         m_properties->set("move_type", m_move_type);
1494         m_properties->setV3F("speed", m_speed);
1495         m_properties->setFloat("age", m_age);
1496         m_properties->setFloat("yaw", m_yaw);
1497         m_properties->setV3F("pos", m_base_position);
1498         m_properties->setS32("hp", m_hp);
1499         m_properties->setFloat("die_age", m_die_age);
1500         m_properties->setV2F("size", m_size);
1501
1502         m_properties->setS32("version", 0);
1503 }
1504
1505 void MobV2SAO::doDamage(u16 d)
1506 {
1507         infostream<<"MobV2 hp="<<m_hp<<" damage="<<d<<std::endl;
1508         
1509         if(d < m_hp)
1510         {
1511                 m_hp -= d;
1512         }
1513         else
1514         {
1515                 actionstream<<"A "<<(isPeaceful()?"peaceful":"non-peaceful")
1516                                 <<" mob id="<<m_id<<" dies at "<<PP(m_base_position)<<std::endl;
1517                 // Die
1518                 m_hp = 0;
1519                 m_removed = true;
1520         }
1521
1522         {
1523                 std::ostringstream os(std::ios::binary);
1524                 // command (1 = damage)
1525                 writeU8(os, 1);
1526                 // amount
1527                 writeU16(os, d);
1528                 // create message and add to list
1529                 ActiveObjectMessage aom(getId(), false, os.str());
1530                 m_messages_out.push_back(aom);
1531         }
1532 }
1533
1534
1535 /*
1536         LuaEntitySAO
1537 */
1538
1539 #include "scriptapi.h"
1540 #include "luaentity_common.h"
1541
1542 // Prototype
1543 LuaEntitySAO proto_LuaEntitySAO(NULL, v3f(0,0,0), "_prototype", "");
1544
1545 LuaEntitySAO::LuaEntitySAO(ServerEnvironment *env, v3f pos,
1546                 const std::string &name, const std::string &state):
1547         ServerActiveObject(env, pos),
1548         m_init_name(name),
1549         m_init_state(state),
1550         m_registered(false),
1551         m_prop(new LuaEntityProperties),
1552         m_velocity(0,0,0),
1553         m_acceleration(0,0,0),
1554         m_yaw(0),
1555         m_last_sent_yaw(0),
1556         m_last_sent_position(0,0,0),
1557         m_last_sent_velocity(0,0,0),
1558         m_last_sent_position_timer(0),
1559         m_last_sent_move_precision(0)
1560 {
1561         // Only register type if no environment supplied
1562         if(env == NULL){
1563                 ServerActiveObject::registerType(getType(), create);
1564                 return;
1565         }
1566 }
1567
1568 LuaEntitySAO::~LuaEntitySAO()
1569 {
1570         if(m_registered){
1571                 lua_State *L = m_env->getLua();
1572                 scriptapi_luaentity_rm(L, m_id);
1573         }
1574         delete m_prop;
1575 }
1576
1577 void LuaEntitySAO::addedToEnvironment()
1578 {
1579         ServerActiveObject::addedToEnvironment();
1580         
1581         // Create entity from name and state
1582         lua_State *L = m_env->getLua();
1583         m_registered = scriptapi_luaentity_add(L, m_id, m_init_name.c_str(),
1584                         m_init_state.c_str());
1585         
1586         if(m_registered){
1587                 // Get properties
1588                 scriptapi_luaentity_get_properties(L, m_id, m_prop);
1589         }
1590 }
1591
1592 ServerActiveObject* LuaEntitySAO::create(ServerEnvironment *env, v3f pos,
1593                 const std::string &data)
1594 {
1595         std::istringstream is(data, std::ios::binary);
1596         // read version
1597         u8 version = readU8(is);
1598         // check if version is supported
1599         if(version != 0)
1600                 return NULL;
1601         // read name
1602         std::string name = deSerializeString(is);
1603         // read state
1604         std::string state = deSerializeLongString(is);
1605         // create object
1606         infostream<<"LuaEntitySAO::create(name=\""<<name<<"\" state=\""
1607                         <<state<<"\")"<<std::endl;
1608         return new LuaEntitySAO(env, pos, name, state);
1609 }
1610
1611 void LuaEntitySAO::step(float dtime, bool send_recommended)
1612 {
1613         m_last_sent_position_timer += dtime;
1614         
1615         if(m_prop->physical){
1616                 core::aabbox3d<f32> box = m_prop->collisionbox;
1617                 box.MinEdge *= BS;
1618                 box.MaxEdge *= BS;
1619                 collisionMoveResult moveresult;
1620                 f32 pos_max_d = BS*0.25; // Distance per iteration
1621                 v3f p_pos = getBasePosition();
1622                 v3f p_velocity = m_velocity;
1623                 IGameDef *gamedef = m_env->getGameDef();
1624                 moveresult = collisionMovePrecise(&m_env->getMap(), gamedef,
1625                                 pos_max_d, box, dtime, p_pos, p_velocity);
1626                 // Apply results
1627                 setBasePosition(p_pos);
1628                 m_velocity = p_velocity;
1629
1630                 m_velocity += dtime * m_acceleration;
1631         } else {
1632                 m_base_position += dtime * m_velocity + 0.5 * dtime
1633                                 * dtime * m_acceleration;
1634                 m_velocity += dtime * m_acceleration;
1635         }
1636
1637         if(m_registered){
1638                 lua_State *L = m_env->getLua();
1639                 scriptapi_luaentity_step(L, m_id, dtime);
1640         }
1641
1642         if(send_recommended == false)
1643                 return;
1644         
1645         // TODO: force send when acceleration changes enough?
1646         float minchange = 0.2*BS;
1647         if(m_last_sent_position_timer > 1.0){
1648                 minchange = 0.01*BS;
1649         } else if(m_last_sent_position_timer > 0.2){
1650                 minchange = 0.05*BS;
1651         }
1652         float move_d = m_base_position.getDistanceFrom(m_last_sent_position);
1653         move_d += m_last_sent_move_precision;
1654         float vel_d = m_velocity.getDistanceFrom(m_last_sent_velocity);
1655         if(move_d > minchange || vel_d > minchange ||
1656                         fabs(m_yaw - m_last_sent_yaw) > 1.0){
1657                 sendPosition(true, false);
1658         }
1659 }
1660
1661 std::string LuaEntitySAO::getClientInitializationData()
1662 {
1663         std::ostringstream os(std::ios::binary);
1664         // version
1665         writeU8(os, 0);
1666         // pos
1667         writeV3F1000(os, m_base_position);
1668         // yaw
1669         writeF1000(os, m_yaw);
1670         // properties
1671         std::ostringstream prop_os(std::ios::binary);
1672         m_prop->serialize(prop_os);
1673         os<<serializeLongString(prop_os.str());
1674         // return result
1675         return os.str();
1676 }
1677
1678 std::string LuaEntitySAO::getStaticData()
1679 {
1680         infostream<<__FUNCTION_NAME<<std::endl;
1681         std::ostringstream os(std::ios::binary);
1682         // version
1683         writeU8(os, 0);
1684         // name
1685         os<<serializeString(m_init_name);
1686         // state
1687         if(m_registered){
1688                 lua_State *L = m_env->getLua();
1689                 std::string state = scriptapi_luaentity_get_staticdata(L, m_id);
1690                 os<<serializeLongString(state);
1691         } else {
1692                 os<<serializeLongString(m_init_state);
1693         }
1694         return os.str();
1695 }
1696
1697 void LuaEntitySAO::punch(ServerActiveObject *puncher, float time_from_last_punch)
1698 {
1699         if(!m_registered){
1700                 // Delete unknown LuaEntities when punched
1701                 m_removed = true;
1702                 return;
1703         }
1704         lua_State *L = m_env->getLua();
1705         scriptapi_luaentity_punch(L, m_id, puncher, time_from_last_punch);
1706 }
1707
1708 void LuaEntitySAO::rightClick(ServerActiveObject *clicker)
1709 {
1710         if(!m_registered)
1711                 return;
1712         lua_State *L = m_env->getLua();
1713         scriptapi_luaentity_rightclick(L, m_id, clicker);
1714 }
1715
1716 void LuaEntitySAO::setPos(v3f pos)
1717 {
1718         m_base_position = pos;
1719         sendPosition(false, true);
1720 }
1721
1722 void LuaEntitySAO::moveTo(v3f pos, bool continuous)
1723 {
1724         m_base_position = pos;
1725         if(!continuous)
1726                 sendPosition(true, true);
1727 }
1728
1729 float LuaEntitySAO::getMinimumSavedMovement()
1730 {
1731         return 0.1 * BS;
1732 }
1733
1734 void LuaEntitySAO::setVelocity(v3f velocity)
1735 {
1736         m_velocity = velocity;
1737 }
1738
1739 v3f LuaEntitySAO::getVelocity()
1740 {
1741         return m_velocity;
1742 }
1743
1744 void LuaEntitySAO::setAcceleration(v3f acceleration)
1745 {
1746         m_acceleration = acceleration;
1747 }
1748
1749 v3f LuaEntitySAO::getAcceleration()
1750 {
1751         return m_acceleration;
1752 }
1753
1754 void LuaEntitySAO::setYaw(float yaw)
1755 {
1756         m_yaw = yaw;
1757 }
1758
1759 float LuaEntitySAO::getYaw()
1760 {
1761         return m_yaw;
1762 }
1763
1764 void LuaEntitySAO::setTextureMod(const std::string &mod)
1765 {
1766         std::ostringstream os(std::ios::binary);
1767         // command (1 = set texture modification)
1768         writeU8(os, 1);
1769         // parameters
1770         os<<serializeString(mod);
1771         // create message and add to list
1772         ActiveObjectMessage aom(getId(), false, os.str());
1773         m_messages_out.push_back(aom);
1774 }
1775
1776 void LuaEntitySAO::setSprite(v2s16 p, int num_frames, float framelength,
1777                 bool select_horiz_by_yawpitch)
1778 {
1779         std::ostringstream os(std::ios::binary);
1780         // command (2 = set sprite)
1781         writeU8(os, 2);
1782         // parameters
1783         writeV2S16(os, p);
1784         writeU16(os, num_frames);
1785         writeF1000(os, framelength);
1786         writeU8(os, select_horiz_by_yawpitch);
1787         // create message and add to list
1788         ActiveObjectMessage aom(getId(), false, os.str());
1789         m_messages_out.push_back(aom);
1790 }
1791
1792 std::string LuaEntitySAO::getName()
1793 {
1794         return m_init_name;
1795 }
1796
1797 void LuaEntitySAO::sendPosition(bool do_interpolate, bool is_movement_end)
1798 {
1799         m_last_sent_move_precision = m_base_position.getDistanceFrom(
1800                         m_last_sent_position);
1801         m_last_sent_position_timer = 0;
1802         m_last_sent_yaw = m_yaw;
1803         m_last_sent_position = m_base_position;
1804         m_last_sent_velocity = m_velocity;
1805         //m_last_sent_acceleration = m_acceleration;
1806
1807         float update_interval = m_env->getSendRecommendedInterval();
1808
1809         std::ostringstream os(std::ios::binary);
1810         // command (0 = update position)
1811         writeU8(os, 0);
1812
1813         // do_interpolate
1814         writeU8(os, do_interpolate);
1815         // pos
1816         writeV3F1000(os, m_base_position);
1817         // velocity
1818         writeV3F1000(os, m_velocity);
1819         // acceleration
1820         writeV3F1000(os, m_acceleration);
1821         // yaw
1822         writeF1000(os, m_yaw);
1823         // is_end_position (for interpolation)
1824         writeU8(os, is_movement_end);
1825         // update_interval (for interpolation)
1826         writeF1000(os, update_interval);
1827
1828         // create message and add to list
1829         ActiveObjectMessage aom(getId(), false, os.str());
1830         m_messages_out.push_back(aom);
1831 }
1832