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