3 Copyright (C) 2010-2011 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
20 #include "content_sao.h"
21 #include "collision.h"
22 #include "environment.h"
24 #include "main.h" // For g_profiler
26 #include "serialization.h" // For compressZlib
27 #include "tool.h" // For ToolCapabilities
30 core::map<u16, ServerActiveObject::Factory> ServerActiveObject::m_types;
32 /* Some helper functions */
34 // Y is copied, X and Z change is limited
35 void accelerate_xz(v3f &speed, v3f target_speed, f32 max_increase)
37 v3f d_wanted = target_speed - speed;
39 f32 dl_wanted = d_wanted.getLength();
44 v3f d = d_wanted.normalize() * dl;
48 speed.Y = target_speed.Y;
56 TestSAO proto_TestSAO(NULL, v3f(0,0,0));
58 TestSAO::TestSAO(ServerEnvironment *env, v3f pos):
59 ServerActiveObject(env, pos),
63 ServerActiveObject::registerType(getType(), create);
66 ServerActiveObject* TestSAO::create(ServerEnvironment *env, v3f pos,
67 const std::string &data)
69 return new TestSAO(env, pos);
72 void TestSAO::step(float dtime, bool send_recommended)
81 m_base_position.Y += dtime * BS * 2;
82 if(m_base_position.Y > 8*BS)
83 m_base_position.Y = 2*BS;
85 if(send_recommended == false)
95 data += itos(0); // 0 = position
97 data += itos(m_base_position.X);
99 data += itos(m_base_position.Y);
101 data += itos(m_base_position.Z);
103 ActiveObjectMessage aom(getId(), false, data);
104 m_messages_out.push_back(aom);
114 ItemSAO proto_ItemSAO(NULL, v3f(0,0,0), "");
116 ItemSAO::ItemSAO(ServerEnvironment *env, v3f pos,
117 const std::string itemstring):
118 ServerActiveObject(env, pos),
119 m_itemstring(itemstring),
120 m_itemstring_changed(false),
122 m_last_sent_position(0,0,0)
124 ServerActiveObject::registerType(getType(), create);
127 ServerActiveObject* ItemSAO::create(ServerEnvironment *env, v3f pos,
128 const std::string &data)
130 std::istringstream is(data, std::ios::binary);
135 // check if version is supported
138 std::string itemstring = deSerializeString(is);
139 infostream<<"ItemSAO::create(): Creating item \""
140 <<itemstring<<"\""<<std::endl;
141 return new ItemSAO(env, pos, itemstring);
144 void ItemSAO::step(float dtime, bool send_recommended)
146 ScopeProfiler sp2(g_profiler, "ItemSAO::step avg", SPT_AVG);
150 const float interval = 0.2;
151 if(m_move_interval.step(dtime, interval)==false)
155 core::aabbox3d<f32> box(-BS/3.,0.0,-BS/3., BS/3.,BS*2./3.,BS/3.);
156 collisionMoveResult moveresult;
158 m_speed_f += v3f(0, -dtime*9.81*BS, 0);
159 // Maximum movement without glitches
160 f32 pos_max_d = BS*0.25;
162 if(m_speed_f.getLength()*dtime > pos_max_d)
163 m_speed_f *= pos_max_d / (m_speed_f.getLength()*dtime);
164 v3f pos_f = getBasePosition();
165 v3f pos_f_old = pos_f;
166 IGameDef *gamedef = m_env->getGameDef();
167 moveresult = collisionMoveSimple(&m_env->getMap(), gamedef,
168 pos_max_d, box, dtime, pos_f, m_speed_f);
170 if(send_recommended == false)
173 if(pos_f.getDistanceFrom(m_last_sent_position) > 0.05*BS)
175 setBasePosition(pos_f);
176 m_last_sent_position = pos_f;
178 std::ostringstream os(std::ios::binary);
179 // command (0 = update position)
182 writeV3F1000(os, m_base_position);
183 // create message and add to list
184 ActiveObjectMessage aom(getId(), false, os.str());
185 m_messages_out.push_back(aom);
187 if(m_itemstring_changed)
189 m_itemstring_changed = false;
191 std::ostringstream os(std::ios::binary);
192 // command (1 = update itemstring)
195 os<<serializeString(m_itemstring);
196 // create message and add to list
197 ActiveObjectMessage aom(getId(), false, os.str());
198 m_messages_out.push_back(aom);
202 std::string ItemSAO::getClientInitializationData()
204 std::ostringstream os(std::ios::binary);
208 writeV3F1000(os, m_base_position);
210 os<<serializeString(m_itemstring);
214 std::string ItemSAO::getStaticData()
216 infostream<<__FUNCTION_NAME<<std::endl;
217 std::ostringstream os(std::ios::binary);
221 os<<serializeString(m_itemstring);
225 ItemStack ItemSAO::createItemStack()
228 IItemDefManager *idef = m_env->getGameDef()->idef();
230 item.deSerialize(m_itemstring, idef);
231 infostream<<__FUNCTION_NAME<<": m_itemstring=\""<<m_itemstring
232 <<"\" -> item=\""<<item.getItemString()<<"\""
236 catch(SerializationError &e)
238 infostream<<__FUNCTION_NAME<<": serialization error: "
239 <<"m_itemstring=\""<<m_itemstring<<"\""<<std::endl;
244 void ItemSAO::punch(ServerActiveObject *puncher, float time_from_last_punch)
246 // Allow removing items in creative mode
247 if(g_settings->getBool("creative_mode") == true)
253 ItemStack item = createItemStack();
254 Inventory *inv = puncher->getInventory();
257 std::string wieldlist = puncher->getWieldList();
258 ItemStack leftover = inv->addItem(wieldlist, item);
259 puncher->setInventoryModified();
266 m_itemstring = leftover.getItemString();
267 m_itemstring_changed = true;
277 RatSAO proto_RatSAO(NULL, v3f(0,0,0));
279 RatSAO::RatSAO(ServerEnvironment *env, v3f pos):
280 ServerActiveObject(env, pos),
284 ServerActiveObject::registerType(getType(), create);
286 m_oldpos = v3f(0,0,0);
287 m_last_sent_position = v3f(0,0,0);
288 m_yaw = myrand_range(0,PI*2);
292 m_touching_ground = false;
295 ServerActiveObject* RatSAO::create(ServerEnvironment *env, v3f pos,
296 const std::string &data)
298 std::istringstream is(data, std::ios::binary);
303 // check if version is supported
306 return new RatSAO(env, pos);
309 void RatSAO::step(float dtime, bool send_recommended)
311 ScopeProfiler sp2(g_profiler, "RatSAO::step avg", SPT_AVG);
315 if(m_is_active == false)
317 if(m_inactive_interval.step(dtime, 0.5)==false)
334 m_speed_f.Y -= dtime*9.81*BS;
337 Move around if some player is close
339 bool player_is_close = false;
340 // Check connected players
341 core::list<Player*> players = m_env->getPlayers(true);
342 core::list<Player*>::Iterator i;
343 for(i = players.begin();
344 i != players.end(); i++)
347 v3f playerpos = player->getPosition();
348 if(m_base_position.getDistanceFrom(playerpos) < BS*10.0)
350 player_is_close = true;
355 m_is_active = player_is_close;
357 if(player_is_close == false)
365 v3f dir(cos(m_yaw/180*PI),0,sin(m_yaw/180*PI));
367 m_speed_f.X = speed * dir.X;
368 m_speed_f.Z = speed * dir.Z;
370 if(m_touching_ground && (m_oldpos - m_base_position).getLength()
377 m_speed_f.Y = 5.0*BS;
385 m_counter2 += (float)(myrand()%100)/100*3.0;
386 m_yaw += ((float)(myrand()%200)-100)/100*180;
387 m_yaw = wrapDegrees(m_yaw);
392 m_oldpos = m_base_position;
395 Move it, with collision detection
398 core::aabbox3d<f32> box(-BS/3.,0.0,-BS/3., BS/3.,BS*2./3.,BS/3.);
399 collisionMoveResult moveresult;
400 // Maximum movement without glitches
401 f32 pos_max_d = BS*0.25;
403 if(m_speed_f.getLength()*dtime > pos_max_d)
404 m_speed_f *= pos_max_d / (m_speed_f.getLength()*dtime);
405 v3f pos_f = getBasePosition();
406 v3f pos_f_old = pos_f;
407 IGameDef *gamedef = m_env->getGameDef();
408 moveresult = collisionMoveSimple(&m_env->getMap(), gamedef,
409 pos_max_d, box, dtime, pos_f, m_speed_f);
410 m_touching_ground = moveresult.touching_ground;
412 setBasePosition(pos_f);
414 if(send_recommended == false)
417 if(pos_f.getDistanceFrom(m_last_sent_position) > 0.05*BS)
419 m_last_sent_position = pos_f;
421 std::ostringstream os(std::ios::binary);
422 // command (0 = update position)
425 writeV3F1000(os, m_base_position);
427 writeF1000(os, m_yaw);
428 // create message and add to list
429 ActiveObjectMessage aom(getId(), false, os.str());
430 m_messages_out.push_back(aom);
434 std::string RatSAO::getClientInitializationData()
436 std::ostringstream os(std::ios::binary);
440 writeV3F1000(os, m_base_position);
444 std::string RatSAO::getStaticData()
446 //infostream<<__FUNCTION_NAME<<std::endl;
447 std::ostringstream os(std::ios::binary);
453 void RatSAO::punch(ServerActiveObject *puncher, float time_from_last_punch)
455 // Allow removing rats in creative mode
456 if(g_settings->getBool("creative_mode") == true)
462 IItemDefManager *idef = m_env->getGameDef()->idef();
463 ItemStack item("rat", 1, 0, "", idef);
464 Inventory *inv = puncher->getInventory();
467 std::string wieldlist = puncher->getWieldList();
468 ItemStack leftover = inv->addItem(wieldlist, item);
469 puncher->setInventoryModified();
480 Oerkki1SAO proto_Oerkki1SAO(NULL, v3f(0,0,0));
482 Oerkki1SAO::Oerkki1SAO(ServerEnvironment *env, v3f pos):
483 ServerActiveObject(env, pos),
487 ServerActiveObject::registerType(getType(), create);
489 m_oldpos = v3f(0,0,0);
490 m_last_sent_position = v3f(0,0,0);
495 m_touching_ground = false;
497 m_after_jump_timer = 0;
500 ServerActiveObject* Oerkki1SAO::create(ServerEnvironment *env, v3f pos,
501 const std::string &data)
503 std::istringstream is(data, std::ios::binary);
505 u8 version = readU8(is);
508 // check if version is supported
511 Oerkki1SAO *o = new Oerkki1SAO(env, pos);
516 void Oerkki1SAO::step(float dtime, bool send_recommended)
518 ScopeProfiler sp2(g_profiler, "Oerkki1SAO::step avg", SPT_AVG);
522 if(m_is_active == false)
524 if(m_inactive_interval.step(dtime, 0.5)==false)
540 m_after_jump_timer -= dtime;
542 v3f old_speed = m_speed_f;
545 m_speed_f.Y -= dtime*9.81*BS;
548 Move around if some player is close
550 bool player_is_close = false;
551 bool player_is_too_close = false;
553 // Check connected players
554 core::list<Player*> players = m_env->getPlayers(true);
555 core::list<Player*>::Iterator i;
556 for(i = players.begin();
557 i != players.end(); i++)
560 v3f playerpos = player->getPosition();
561 f32 dist = m_base_position.getDistanceFrom(playerpos);
566 player_is_too_close = true;
567 near_player_pos = playerpos;
569 else if(dist < BS*15.0 && !player_is_too_close)
571 player_is_close = true;
572 near_player_pos = playerpos;
576 m_is_active = player_is_close;
578 v3f target_speed = m_speed_f;
582 target_speed = v3f(0,0,0);
588 v3f ndir = near_player_pos - m_base_position;
592 f32 nyaw = 180./PI*atan2(ndir.Z,ndir.X);
593 if(nyaw < m_yaw - 180)
595 else if(nyaw > m_yaw + 180)
597 m_yaw = 0.95*m_yaw + 0.05*nyaw;
598 m_yaw = wrapDegrees(m_yaw);
602 if((m_touching_ground || m_after_jump_timer > 0.0)
603 && !player_is_too_close)
605 v3f dir(cos(m_yaw/180*PI),0,sin(m_yaw/180*PI));
606 target_speed.X = speed * dir.X;
607 target_speed.Z = speed * dir.Z;
610 if(m_touching_ground && (m_oldpos - m_base_position).getLength()
618 target_speed.Y = 5.0*BS;
619 m_after_jump_timer = 1.0;
627 m_counter2 += (float)(myrand()%100)/100*3.0;
628 //m_yaw += ((float)(myrand()%200)-100)/100*180;
629 m_yaw += ((float)(myrand()%200)-100)/100*90;
630 m_yaw = wrapDegrees(m_yaw);
635 if((m_speed_f - target_speed).getLength() > BS*4 || player_is_too_close)
636 accelerate_xz(m_speed_f, target_speed, dtime*BS*8);
638 accelerate_xz(m_speed_f, target_speed, dtime*BS*4);
640 m_oldpos = m_base_position;
643 Move it, with collision detection
646 core::aabbox3d<f32> box(-BS/3.,0.0,-BS/3., BS/3.,BS*5./3.,BS/3.);
647 collisionMoveResult moveresult;
648 // Maximum movement without glitches
649 f32 pos_max_d = BS*0.25;
651 if(m_speed_f.getLength()*dtime > pos_max_d)
652 m_speed_f *= pos_max_d / (m_speed_f.getLength()*dtime);*/
653 v3f pos_f = getBasePosition();
654 v3f pos_f_old = pos_f;
655 IGameDef *gamedef = m_env->getGameDef();
656 moveresult = collisionMovePrecise(&m_env->getMap(), gamedef,
657 pos_max_d, box, dtime, pos_f, m_speed_f);
658 m_touching_ground = moveresult.touching_ground;
660 // Do collision damage
661 float tolerance = BS*30;
662 float factor = BS*0.5;
663 v3f speed_diff = old_speed - m_speed_f;
664 // Increase effect in X and Z
667 float vel = speed_diff.getLength();
670 f32 damage_f = (vel - tolerance)/BS*factor;
671 u16 damage = (u16)(damage_f+0.5);
675 setBasePosition(pos_f);
677 if(send_recommended == false && m_speed_f.getLength() < 3.0*BS)
680 if(pos_f.getDistanceFrom(m_last_sent_position) > 0.05*BS)
682 m_last_sent_position = pos_f;
684 std::ostringstream os(std::ios::binary);
685 // command (0 = update position)
688 writeV3F1000(os, m_base_position);
690 writeF1000(os, m_yaw);
691 // create message and add to list
692 ActiveObjectMessage aom(getId(), false, os.str());
693 m_messages_out.push_back(aom);
697 std::string Oerkki1SAO::getClientInitializationData()
699 std::ostringstream os(std::ios::binary);
703 writeV3F1000(os, m_base_position);
707 std::string Oerkki1SAO::getStaticData()
709 //infostream<<__FUNCTION_NAME<<std::endl;
710 std::ostringstream os(std::ios::binary);
718 void Oerkki1SAO::punch(ServerActiveObject *puncher, float time_from_last_punch)
723 v3f dir = (getBasePosition() - puncher->getBasePosition()).normalize();
724 m_speed_f += dir*12*BS;
726 // "Material" groups of the object
727 ItemGroupList groups;
728 groups["snappy"] = 1;
729 groups["choppy"] = 1;
730 groups["fleshy"] = 3;
732 IItemDefManager *idef = m_env->getGameDef()->idef();
733 ItemStack punchitem = puncher->getWieldedItem();
734 ToolCapabilities tp = punchitem.getToolCapabilities(idef);
736 HitParams hit_params = getHitParams(groups, &tp,
737 time_from_last_punch);
739 doDamage(hit_params.hp);
740 if(g_settings->getBool("creative_mode") == false)
742 punchitem.addWear(hit_params.wear, idef);
743 puncher->setWieldedItem(punchitem);
747 void Oerkki1SAO::doDamage(u16 d)
749 infostream<<"oerkki damage: "<<d<<std::endl;
763 std::ostringstream os(std::ios::binary);
764 // command (1 = damage)
768 // create message and add to list
769 ActiveObjectMessage aom(getId(), false, os.str());
770 m_messages_out.push_back(aom);
779 FireflySAO proto_FireflySAO(NULL, v3f(0,0,0));
781 FireflySAO::FireflySAO(ServerEnvironment *env, v3f pos):
782 ServerActiveObject(env, pos),
786 ServerActiveObject::registerType(getType(), create);
788 m_oldpos = v3f(0,0,0);
789 m_last_sent_position = v3f(0,0,0);
794 m_touching_ground = false;
797 ServerActiveObject* FireflySAO::create(ServerEnvironment *env, v3f pos,
798 const std::string &data)
800 std::istringstream is(data, std::ios::binary);
805 // check if version is supported
808 return new FireflySAO(env, pos);
811 void FireflySAO::step(float dtime, bool send_recommended)
813 ScopeProfiler sp2(g_profiler, "FireflySAO::step avg", SPT_AVG);
817 if(m_is_active == false)
819 if(m_inactive_interval.step(dtime, 0.5)==false)
827 // Apply (less) gravity
828 m_speed_f.Y -= dtime*3*BS;
831 Move around if some player is close
833 bool player_is_close = false;
834 // Check connected players
835 core::list<Player*> players = m_env->getPlayers(true);
836 core::list<Player*>::Iterator i;
837 for(i = players.begin();
838 i != players.end(); i++)
841 v3f playerpos = player->getPosition();
842 if(m_base_position.getDistanceFrom(playerpos) < BS*10.0)
844 player_is_close = true;
849 m_is_active = player_is_close;
851 if(player_is_close == false)
859 v3f dir(cos(m_yaw/180*PI),0,sin(m_yaw/180*PI));
861 m_speed_f.X = speed * dir.X;
862 m_speed_f.Z = speed * dir.Z;
864 if(m_touching_ground && (m_oldpos - m_base_position).getLength()
871 m_speed_f.Y = 5.0*BS;
879 m_counter2 += (float)(myrand()%100)/100*3.0;
880 m_yaw += ((float)(myrand()%200)-100)/100*180;
881 m_yaw = wrapDegrees(m_yaw);
886 m_oldpos = m_base_position;
889 Move it, with collision detection
892 core::aabbox3d<f32> box(-BS/3.,-BS*2/3.0,-BS/3., BS/3.,BS*4./3.,BS/3.);
893 collisionMoveResult moveresult;
894 // Maximum movement without glitches
895 f32 pos_max_d = BS*0.25;
897 if(m_speed_f.getLength()*dtime > pos_max_d)
898 m_speed_f *= pos_max_d / (m_speed_f.getLength()*dtime);
899 v3f pos_f = getBasePosition();
900 v3f pos_f_old = pos_f;
901 IGameDef *gamedef = m_env->getGameDef();
902 moveresult = collisionMoveSimple(&m_env->getMap(), gamedef,
903 pos_max_d, box, dtime, pos_f, m_speed_f);
904 m_touching_ground = moveresult.touching_ground;
906 setBasePosition(pos_f);
908 if(send_recommended == false)
911 if(pos_f.getDistanceFrom(m_last_sent_position) > 0.05*BS)
913 m_last_sent_position = pos_f;
915 std::ostringstream os(std::ios::binary);
916 // command (0 = update position)
919 writeV3F1000(os, m_base_position);
921 writeF1000(os, m_yaw);
922 // create message and add to list
923 ActiveObjectMessage aom(getId(), false, os.str());
924 m_messages_out.push_back(aom);
928 std::string FireflySAO::getClientInitializationData()
930 std::ostringstream os(std::ios::binary);
934 writeV3F1000(os, m_base_position);
938 std::string FireflySAO::getStaticData()
940 //infostream<<__FUNCTION_NAME<<std::endl;
941 std::ostringstream os(std::ios::binary);
952 MobV2SAO proto_MobV2SAO(NULL, v3f(0,0,0), NULL);
954 MobV2SAO::MobV2SAO(ServerEnvironment *env, v3f pos,
955 Settings *init_properties):
956 ServerActiveObject(env, pos),
957 m_move_type("ground_nodes"),
959 m_last_sent_position(0,0,0),
965 m_touching_ground(false),
967 m_walk_around(false),
968 m_walk_around_timer(0),
969 m_next_pos_exists(false),
970 m_shoot_reload_timer(0),
974 m_disturb_timer(100000),
975 m_random_disturb_timer(0),
978 ServerActiveObject::registerType(getType(), create);
980 m_properties = new Settings();
982 m_properties->update(*init_properties);
984 m_properties->setV3F("pos", pos);
986 setPropertyDefaults();
990 MobV2SAO::~MobV2SAO()
995 ServerActiveObject* MobV2SAO::create(ServerEnvironment *env, v3f pos,
996 const std::string &data)
998 std::istringstream is(data, std::ios::binary);
1000 properties.parseConfigLines(is, "MobArgsEnd");
1001 MobV2SAO *o = new MobV2SAO(env, pos, &properties);
1005 std::string MobV2SAO::getStaticData()
1009 std::ostringstream os(std::ios::binary);
1010 m_properties->writeLines(os);
1014 std::string MobV2SAO::getClientInitializationData()
1016 //infostream<<__FUNCTION_NAME<<std::endl;
1020 std::ostringstream os(std::ios::binary);
1025 Settings client_properties;
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");*/
1032 // Just send everything for simplicity
1033 client_properties.update(*m_properties);
1035 std::ostringstream os2(std::ios::binary);
1036 client_properties.writeLines(os2);
1037 compressZlib(os2.str(), os);
1042 bool checkFreePosition(Map *map, v3s16 p0, v3s16 size)
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);
1049 MapNode n = map->getNodeNoEx(p);
1050 if(n.getContent() != CONTENT_AIR)
1056 bool checkWalkablePosition(Map *map, v3s16 p0)
1058 v3s16 p = p0 + v3s16(0,-1,0);
1059 MapNode n = map->getNodeNoEx(p);
1060 if(n.getContent() != CONTENT_AIR)
1065 bool checkFreeAndWalkablePosition(Map *map, v3s16 p0, v3s16 size)
1067 if(!checkFreePosition(map, p0, size))
1069 if(!checkWalkablePosition(map, p0))
1074 static void get_random_u32_array(u32 a[], u32 len)
1077 for(i=0; i<len; i++)
1081 u32 k = myrand() % n;
1089 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
1091 static void explodeSquare(Map *map, v3s16 p0, v3s16 size)
1093 core::map<v3s16, MapBlock*> modified_blocks;
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);
1100 MapNode n = map->getNodeNoEx(p);
1101 if(n.getContent() == CONTENT_IGNORE)
1103 //map->removeNodeWithEvent(p);
1104 map->removeNodeAndUpdate(p, modified_blocks);
1107 // Send a MEET_OTHER event
1109 event.type = MEET_OTHER;
1110 for(core::map<v3s16, MapBlock*>::Iterator
1111 i = modified_blocks.getIterator();
1112 i.atEnd() == false; i++)
1114 v3s16 p = i.getNode()->getKey();
1115 event.modified_blocks.insert(p, true);
1117 map->dispatchEvent(&event);
1120 void MobV2SAO::step(float dtime, bool send_recommended)
1122 ScopeProfiler sp2(g_profiler, "MobV2SAO::step avg", SPT_AVG);
1125 Map *map = &m_env->getMap();
1129 if(m_die_age >= 0.0 && m_age >= m_die_age){
1134 m_random_disturb_timer += dtime;
1135 if(m_random_disturb_timer >= 5.0)
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++)
1144 Player *player = *i;
1145 v3f playerpos = player->getPosition();
1146 f32 dist = m_base_position.getDistanceFrom(playerpos);
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;
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);
1178 m_disturb_timer += dtime;
1182 m_shooting_timer -= dtime;
1183 if(m_shooting_timer <= 0.0 && m_shooting){
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));
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,
1210 //m_env->addActiveObjectAsStatic(obj);
1211 m_env->addActiveObject(obj);
1213 infostream<<__FUNCTION_NAME<<": Mob id="<<m_id
1214 <<": Unknown shoot_type="<<shoot_type
1219 m_shoot_reload_timer += dtime;
1221 float reload_time = 15.0;
1222 if(m_disturb_timer <= 15.0)
1225 bool shoot_without_player = false;
1226 if(m_properties->getBool("mindless_rage"))
1227 shoot_without_player = true;
1229 if(!m_shooting && m_shoot_reload_timer >= reload_time &&
1230 !m_next_pos_exists &&
1231 (m_disturb_timer <= 60.0 || shoot_without_player))
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;
1239 m_shoot_y += disturbing_player_norm.Y;
1241 m_shoot_y = 0.01 * myrand_range(-30,10);
1243 m_shoot_reload_timer = 0.0;
1245 m_shooting_timer = 1.5;
1247 std::ostringstream os(std::ios::binary);
1248 // command (2 = shooting)
1251 writeF1000(os, m_shooting_timer + 0.1);
1254 // create message and add to list
1255 ActiveObjectMessage aom(getId(), false, os.str());
1256 m_messages_out.push_back(aom);
1261 if(m_move_type == "ground_nodes")
1264 m_walk_around_timer -= dtime;
1265 if(m_walk_around_timer <= 0.0){
1266 m_walk_around = !m_walk_around;
1268 m_walk_around_timer = 0.1*myrand_range(10,50);
1270 m_walk_around_timer = 0.1*myrand_range(30,70);
1275 if(m_next_pos_exists){
1276 v3f pos_f = m_base_position;
1277 v3f next_pos_f = intToFloat(m_next_pos_i, BS);
1279 v3f v = next_pos_f - pos_f;
1280 m_yaw = atan2(v.Z, v.X) / PI * 180;
1282 v3f diff = next_pos_f - pos_f;
1285 float speed = BS * 0.5;
1288 dir *= dtime * speed;
1289 bool arrived = false;
1290 if(dir.getLength() > diff.getLength()){
1295 m_base_position = pos_f;
1297 if((pos_f - next_pos_f).getLength() < 0.1 || arrived){
1298 m_next_pos_exists = false;
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;
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;
1324 if(!m_next_pos_exists){
1325 /* Find some position where to go next */
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)
1333 if(dx != 0 && dz != 0 && dy != 0)
1335 dps[num_dps++] = v3s16(dx,dy,dz);
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);
1346 m_next_pos_exists = true;
1352 else if(m_move_type == "constant_speed")
1354 m_base_position += m_speed * dtime;
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;
1363 bool free = checkFreePosition(map, pos_i + pos_size_off, size_blocks);
1365 explodeSquare(map, pos_i, v3s16(3,3,3));
1372 errorstream<<"MobV2SAO::step(): id="<<m_id<<" unknown move_type=\""
1373 <<m_move_type<<"\""<<std::endl;
1376 if(send_recommended == false)
1379 if(m_base_position.getDistanceFrom(m_last_sent_position) > 0.05*BS)
1385 void MobV2SAO::punch(ServerActiveObject *puncher, float time_from_last_punch)
1390 v3f dir = (getBasePosition() - puncher->getBasePosition()).normalize();
1392 // A quick hack; SAO description is player name for player
1393 std::string playername = puncher->getDescription();
1395 Map *map = &m_env->getMap();
1397 actionstream<<playername<<" punches mob id="<<m_id
1398 <<" at "<<PP(m_base_position/BS)<<std::endl;
1400 m_disturb_timer = 0;
1401 m_disturbing_player = playername;
1402 m_next_pos_exists = false; // Cancel moving immediately
1404 m_yaw = wrapDegrees_180(180./PI*atan2(dir.Z, dir.X) + 180.);
1405 v3f new_base_position = m_base_position + dir * BS;
1407 v3s16 pos_i = floatToInt(new_base_position, BS);
1408 v3s16 size_blocks = v3s16(m_size.X+0.5,m_size.Y+0.5,m_size.X+0.5);
1409 v3s16 pos_size_off(0,0,0);
1410 if(m_size.X >= 2.5){
1411 pos_size_off.X = -1;
1412 pos_size_off.Y = -1;
1414 bool free = checkFreePosition(map, pos_i + pos_size_off, size_blocks);
1416 m_base_position = new_base_position;
1421 // "Material" groups of the object
1422 ItemGroupList groups;
1423 groups["snappy"] = 1;
1424 groups["choppy"] = 1;
1425 groups["fleshy"] = 3;
1427 IItemDefManager *idef = m_env->getGameDef()->idef();
1428 ItemStack punchitem = puncher->getWieldedItem();
1429 ToolCapabilities tp = punchitem.getToolCapabilities(idef);
1431 HitParams hit_params = getHitParams(groups, &tp,
1432 time_from_last_punch);
1434 doDamage(hit_params.hp);
1435 if(g_settings->getBool("creative_mode") == false)
1437 punchitem.addWear(hit_params.wear, idef);
1438 puncher->setWieldedItem(punchitem);
1442 bool MobV2SAO::isPeaceful()
1444 return m_properties->getBool("is_peaceful");
1447 void MobV2SAO::sendPosition()
1449 m_last_sent_position = m_base_position;
1451 std::ostringstream os(std::ios::binary);
1452 // command (0 = update position)
1455 writeV3F1000(os, m_base_position);
1457 writeF1000(os, m_yaw);
1458 // create message and add to list
1459 ActiveObjectMessage aom(getId(), false, os.str());
1460 m_messages_out.push_back(aom);
1463 void MobV2SAO::setPropertyDefaults()
1465 m_properties->setDefault("is_peaceful", "false");
1466 m_properties->setDefault("move_type", "ground_nodes");
1467 m_properties->setDefault("speed", "(0,0,0)");
1468 m_properties->setDefault("age", "0");
1469 m_properties->setDefault("yaw", "0");
1470 m_properties->setDefault("pos", "(0,0,0)");
1471 m_properties->setDefault("hp", "0");
1472 m_properties->setDefault("die_age", "-1");
1473 m_properties->setDefault("size", "(1,2)");
1474 m_properties->setDefault("shoot_type", "fireball");
1475 m_properties->setDefault("shoot_y", "0");
1476 m_properties->setDefault("mindless_rage", "false");
1478 void MobV2SAO::readProperties()
1480 m_move_type = m_properties->get("move_type");
1481 m_speed = m_properties->getV3F("speed");
1482 m_age = m_properties->getFloat("age");
1483 m_yaw = m_properties->getFloat("yaw");
1484 m_base_position = m_properties->getV3F("pos");
1485 m_hp = m_properties->getS32("hp");
1486 m_die_age = m_properties->getFloat("die_age");
1487 m_size = m_properties->getV2F("size");
1489 void MobV2SAO::updateProperties()
1491 m_properties->set("move_type", m_move_type);
1492 m_properties->setV3F("speed", m_speed);
1493 m_properties->setFloat("age", m_age);
1494 m_properties->setFloat("yaw", m_yaw);
1495 m_properties->setV3F("pos", m_base_position);
1496 m_properties->setS32("hp", m_hp);
1497 m_properties->setFloat("die_age", m_die_age);
1498 m_properties->setV2F("size", m_size);
1500 m_properties->setS32("version", 0);
1503 void MobV2SAO::doDamage(u16 d)
1506 actionstream<<"MobV2 ("<<m_hp<<"hp) takes "<<d<<"hp of damage"<<std::endl;
1514 actionstream<<"A "<<(isPeaceful()?"peaceful":"non-peaceful")
1515 <<" mob id="<<m_id<<" dies at "<<PP(m_base_position)<<std::endl;
1522 std::ostringstream os(std::ios::binary);
1523 // command (1 = damage)
1527 // create message and add to list
1528 ActiveObjectMessage aom(getId(), false, os.str());
1529 m_messages_out.push_back(aom);
1538 #include "scriptapi.h"
1539 #include "luaentity_common.h"
1542 LuaEntitySAO proto_LuaEntitySAO(NULL, v3f(0,0,0), "_prototype", "");
1544 LuaEntitySAO::LuaEntitySAO(ServerEnvironment *env, v3f pos,
1545 const std::string &name, const std::string &state):
1546 ServerActiveObject(env, pos),
1548 m_init_state(state),
1549 m_registered(false),
1550 m_prop(new LuaEntityProperties),
1552 m_acceleration(0,0,0),
1555 m_last_sent_position(0,0,0),
1556 m_last_sent_velocity(0,0,0),
1557 m_last_sent_position_timer(0),
1558 m_last_sent_move_precision(0)
1560 // Only register type if no environment supplied
1562 ServerActiveObject::registerType(getType(), create);
1567 LuaEntitySAO::~LuaEntitySAO()
1570 lua_State *L = m_env->getLua();
1571 scriptapi_luaentity_rm(L, m_id);
1576 void LuaEntitySAO::addedToEnvironment()
1578 ServerActiveObject::addedToEnvironment();
1580 // Create entity from name and state
1581 lua_State *L = m_env->getLua();
1582 m_registered = scriptapi_luaentity_add(L, m_id, m_init_name.c_str(),
1583 m_init_state.c_str());
1587 scriptapi_luaentity_get_properties(L, m_id, m_prop);
1591 ServerActiveObject* LuaEntitySAO::create(ServerEnvironment *env, v3f pos,
1592 const std::string &data)
1594 std::istringstream is(data, std::ios::binary);
1596 u8 version = readU8(is);
1597 // check if version is supported
1601 std::string name = deSerializeString(is);
1603 std::string state = deSerializeLongString(is);
1605 infostream<<"LuaEntitySAO::create(name=\""<<name<<"\" state=\""
1606 <<state<<"\")"<<std::endl;
1607 return new LuaEntitySAO(env, pos, name, state);
1610 void LuaEntitySAO::step(float dtime, bool send_recommended)
1612 m_last_sent_position_timer += dtime;
1614 if(m_prop->physical){
1615 core::aabbox3d<f32> box = m_prop->collisionbox;
1618 collisionMoveResult moveresult;
1619 f32 pos_max_d = BS*0.25; // Distance per iteration
1620 v3f p_pos = getBasePosition();
1621 v3f p_velocity = m_velocity;
1622 IGameDef *gamedef = m_env->getGameDef();
1623 moveresult = collisionMovePrecise(&m_env->getMap(), gamedef,
1624 pos_max_d, box, dtime, p_pos, p_velocity);
1626 setBasePosition(p_pos);
1627 m_velocity = p_velocity;
1629 m_velocity += dtime * m_acceleration;
1631 m_base_position += dtime * m_velocity + 0.5 * dtime
1632 * dtime * m_acceleration;
1633 m_velocity += dtime * m_acceleration;
1637 lua_State *L = m_env->getLua();
1638 scriptapi_luaentity_step(L, m_id, dtime);
1641 if(send_recommended == false)
1644 // TODO: force send when acceleration changes enough?
1645 float minchange = 0.2*BS;
1646 if(m_last_sent_position_timer > 1.0){
1647 minchange = 0.01*BS;
1648 } else if(m_last_sent_position_timer > 0.2){
1649 minchange = 0.05*BS;
1651 float move_d = m_base_position.getDistanceFrom(m_last_sent_position);
1652 move_d += m_last_sent_move_precision;
1653 float vel_d = m_velocity.getDistanceFrom(m_last_sent_velocity);
1654 if(move_d > minchange || vel_d > minchange ||
1655 fabs(m_yaw - m_last_sent_yaw) > 1.0){
1656 sendPosition(true, false);
1660 std::string LuaEntitySAO::getClientInitializationData()
1662 std::ostringstream os(std::ios::binary);
1666 writeV3F1000(os, m_base_position);
1668 writeF1000(os, m_yaw);
1670 std::ostringstream prop_os(std::ios::binary);
1671 m_prop->serialize(prop_os);
1672 os<<serializeLongString(prop_os.str());
1677 std::string LuaEntitySAO::getStaticData()
1679 infostream<<__FUNCTION_NAME<<std::endl;
1680 std::ostringstream os(std::ios::binary);
1684 os<<serializeString(m_init_name);
1687 lua_State *L = m_env->getLua();
1688 std::string state = scriptapi_luaentity_get_staticdata(L, m_id);
1689 os<<serializeLongString(state);
1691 os<<serializeLongString(m_init_state);
1696 void LuaEntitySAO::punch(ServerActiveObject *puncher, float time_from_last_punch)
1699 // Delete unknown LuaEntities when punched
1703 lua_State *L = m_env->getLua();
1704 scriptapi_luaentity_punch(L, m_id, puncher, time_from_last_punch);
1707 void LuaEntitySAO::rightClick(ServerActiveObject *clicker)
1711 lua_State *L = m_env->getLua();
1712 scriptapi_luaentity_rightclick(L, m_id, clicker);
1715 void LuaEntitySAO::setPos(v3f pos)
1717 m_base_position = pos;
1718 sendPosition(false, true);
1721 void LuaEntitySAO::moveTo(v3f pos, bool continuous)
1723 m_base_position = pos;
1725 sendPosition(true, true);
1728 float LuaEntitySAO::getMinimumSavedMovement()
1733 void LuaEntitySAO::setVelocity(v3f velocity)
1735 m_velocity = velocity;
1738 v3f LuaEntitySAO::getVelocity()
1743 void LuaEntitySAO::setAcceleration(v3f acceleration)
1745 m_acceleration = acceleration;
1748 v3f LuaEntitySAO::getAcceleration()
1750 return m_acceleration;
1753 void LuaEntitySAO::setYaw(float yaw)
1758 float LuaEntitySAO::getYaw()
1763 void LuaEntitySAO::setTextureMod(const std::string &mod)
1765 std::ostringstream os(std::ios::binary);
1766 // command (1 = set texture modification)
1769 os<<serializeString(mod);
1770 // create message and add to list
1771 ActiveObjectMessage aom(getId(), false, os.str());
1772 m_messages_out.push_back(aom);
1775 void LuaEntitySAO::setSprite(v2s16 p, int num_frames, float framelength,
1776 bool select_horiz_by_yawpitch)
1778 std::ostringstream os(std::ios::binary);
1779 // command (2 = set sprite)
1783 writeU16(os, num_frames);
1784 writeF1000(os, framelength);
1785 writeU8(os, select_horiz_by_yawpitch);
1786 // create message and add to list
1787 ActiveObjectMessage aom(getId(), false, os.str());
1788 m_messages_out.push_back(aom);
1791 std::string LuaEntitySAO::getName()
1796 void LuaEntitySAO::sendPosition(bool do_interpolate, bool is_movement_end)
1798 m_last_sent_move_precision = m_base_position.getDistanceFrom(
1799 m_last_sent_position);
1800 m_last_sent_position_timer = 0;
1801 m_last_sent_yaw = m_yaw;
1802 m_last_sent_position = m_base_position;
1803 m_last_sent_velocity = m_velocity;
1804 //m_last_sent_acceleration = m_acceleration;
1806 float update_interval = m_env->getSendRecommendedInterval();
1808 std::ostringstream os(std::ios::binary);
1809 // command (0 = update position)
1813 writeU8(os, do_interpolate);
1815 writeV3F1000(os, m_base_position);
1817 writeV3F1000(os, m_velocity);
1819 writeV3F1000(os, m_acceleration);
1821 writeF1000(os, m_yaw);
1822 // is_end_position (for interpolation)
1823 writeU8(os, is_movement_end);
1824 // update_interval (for interpolation)
1825 writeF1000(os, update_interval);
1827 // create message and add to list
1828 ActiveObjectMessage aom(getId(), false, os.str());
1829 m_messages_out.push_back(aom);