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