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