content_sao.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535
  1. /*
  2. Minetest
  3. Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include "content_sao.h"
  17. #include "util/serialize.h"
  18. #include "collision.h"
  19. #include "environment.h"
  20. #include "tool.h" // For ToolCapabilities
  21. #include "gamedef.h"
  22. #include "nodedef.h"
  23. #include "remoteplayer.h"
  24. #include "server.h"
  25. #include "scripting_server.h"
  26. #include "genericobject.h"
  27. #include "settings.h"
  28. #include <algorithm>
  29. #include <cmath>
  30. std::map<u16, ServerActiveObject::Factory> ServerActiveObject::m_types;
  31. /*
  32. TestSAO
  33. */
  34. class TestSAO : public ServerActiveObject
  35. {
  36. public:
  37. TestSAO(ServerEnvironment *env, v3f pos):
  38. ServerActiveObject(env, pos),
  39. m_timer1(0),
  40. m_age(0)
  41. {
  42. ServerActiveObject::registerType(getType(), create);
  43. }
  44. ActiveObjectType getType() const
  45. { return ACTIVEOBJECT_TYPE_TEST; }
  46. static ServerActiveObject* create(ServerEnvironment *env, v3f pos,
  47. const std::string &data)
  48. {
  49. return new TestSAO(env, pos);
  50. }
  51. void step(float dtime, bool send_recommended)
  52. {
  53. m_age += dtime;
  54. if(m_age > 10)
  55. {
  56. m_pending_removal = true;
  57. return;
  58. }
  59. m_base_position.Y += dtime * BS * 2;
  60. if(m_base_position.Y > 8*BS)
  61. m_base_position.Y = 2*BS;
  62. if (!send_recommended)
  63. return;
  64. m_timer1 -= dtime;
  65. if(m_timer1 < 0.0)
  66. {
  67. m_timer1 += 0.125;
  68. std::string data;
  69. data += itos(0); // 0 = position
  70. data += " ";
  71. data += itos(m_base_position.X);
  72. data += " ";
  73. data += itos(m_base_position.Y);
  74. data += " ";
  75. data += itos(m_base_position.Z);
  76. ActiveObjectMessage aom(getId(), false, data);
  77. m_messages_out.push(aom);
  78. }
  79. }
  80. bool getCollisionBox(aabb3f *toset) const { return false; }
  81. virtual bool getSelectionBox(aabb3f *toset) const { return false; }
  82. bool collideWithObjects() const { return false; }
  83. private:
  84. float m_timer1;
  85. float m_age;
  86. };
  87. // Prototype (registers item for deserialization)
  88. TestSAO proto_TestSAO(NULL, v3f(0,0,0));
  89. /*
  90. UnitSAO
  91. */
  92. UnitSAO::UnitSAO(ServerEnvironment *env, v3f pos):
  93. ServerActiveObject(env, pos)
  94. {
  95. // Initialize something to armor groups
  96. m_armor_groups["fleshy"] = 100;
  97. }
  98. ServerActiveObject *UnitSAO::getParent() const
  99. {
  100. if (!m_attachment_parent_id)
  101. return nullptr;
  102. // Check if the parent still exists
  103. ServerActiveObject *obj = m_env->getActiveObject(m_attachment_parent_id);
  104. return obj;
  105. }
  106. void UnitSAO::setArmorGroups(const ItemGroupList &armor_groups)
  107. {
  108. m_armor_groups = armor_groups;
  109. m_armor_groups_sent = false;
  110. }
  111. const ItemGroupList &UnitSAO::getArmorGroups() const
  112. {
  113. return m_armor_groups;
  114. }
  115. void UnitSAO::setAnimation(v2f frame_range, float frame_speed, float frame_blend, bool frame_loop)
  116. {
  117. // store these so they can be updated to clients
  118. m_animation_range = frame_range;
  119. m_animation_speed = frame_speed;
  120. m_animation_blend = frame_blend;
  121. m_animation_loop = frame_loop;
  122. m_animation_sent = false;
  123. }
  124. void UnitSAO::getAnimation(v2f *frame_range, float *frame_speed, float *frame_blend, bool *frame_loop)
  125. {
  126. *frame_range = m_animation_range;
  127. *frame_speed = m_animation_speed;
  128. *frame_blend = m_animation_blend;
  129. *frame_loop = m_animation_loop;
  130. }
  131. void UnitSAO::setAnimationSpeed(float frame_speed)
  132. {
  133. m_animation_speed = frame_speed;
  134. m_animation_speed_sent = false;
  135. }
  136. void UnitSAO::setBonePosition(const std::string &bone, v3f position, v3f rotation)
  137. {
  138. // store these so they can be updated to clients
  139. m_bone_position[bone] = core::vector2d<v3f>(position, rotation);
  140. m_bone_position_sent = false;
  141. }
  142. void UnitSAO::getBonePosition(const std::string &bone, v3f *position, v3f *rotation)
  143. {
  144. *position = m_bone_position[bone].X;
  145. *rotation = m_bone_position[bone].Y;
  146. }
  147. void UnitSAO::setAttachment(int parent_id, const std::string &bone, v3f position, v3f rotation)
  148. {
  149. // Attachments need to be handled on both the server and client.
  150. // If we just attach on the server, we can only copy the position of the parent. Attachments
  151. // are still sent to clients at an interval so players might see them lagging, plus we can't
  152. // read and attach to skeletal bones.
  153. // If we just attach on the client, the server still sees the child at its original location.
  154. // This breaks some things so we also give the server the most accurate representation
  155. // even if players only see the client changes.
  156. int old_parent = m_attachment_parent_id;
  157. m_attachment_parent_id = parent_id;
  158. m_attachment_bone = bone;
  159. m_attachment_position = position;
  160. m_attachment_rotation = rotation;
  161. m_attachment_sent = false;
  162. if (parent_id != old_parent) {
  163. onDetach(old_parent);
  164. onAttach(parent_id);
  165. }
  166. }
  167. void UnitSAO::getAttachment(int *parent_id, std::string *bone, v3f *position,
  168. v3f *rotation) const
  169. {
  170. *parent_id = m_attachment_parent_id;
  171. *bone = m_attachment_bone;
  172. *position = m_attachment_position;
  173. *rotation = m_attachment_rotation;
  174. }
  175. void UnitSAO::clearChildAttachments()
  176. {
  177. for (int child_id : m_attachment_child_ids) {
  178. // Child can be NULL if it was deleted earlier
  179. if (ServerActiveObject *child = m_env->getActiveObject(child_id))
  180. child->setAttachment(0, "", v3f(0, 0, 0), v3f(0, 0, 0));
  181. }
  182. m_attachment_child_ids.clear();
  183. }
  184. void UnitSAO::clearParentAttachment()
  185. {
  186. ServerActiveObject *parent = nullptr;
  187. if (m_attachment_parent_id) {
  188. parent = m_env->getActiveObject(m_attachment_parent_id);
  189. setAttachment(0, "", m_attachment_position, m_attachment_rotation);
  190. } else {
  191. setAttachment(0, "", v3f(0, 0, 0), v3f(0, 0, 0));
  192. }
  193. // Do it
  194. if (parent)
  195. parent->removeAttachmentChild(m_id);
  196. }
  197. void UnitSAO::addAttachmentChild(int child_id)
  198. {
  199. m_attachment_child_ids.insert(child_id);
  200. }
  201. void UnitSAO::removeAttachmentChild(int child_id)
  202. {
  203. m_attachment_child_ids.erase(child_id);
  204. }
  205. const std::unordered_set<int> &UnitSAO::getAttachmentChildIds() const
  206. {
  207. return m_attachment_child_ids;
  208. }
  209. void UnitSAO::onAttach(int parent_id)
  210. {
  211. if (!parent_id)
  212. return;
  213. ServerActiveObject *parent = m_env->getActiveObject(parent_id);
  214. if (!parent || parent->isGone())
  215. return; // Do not try to notify soon gone parent
  216. if (parent->getType() == ACTIVEOBJECT_TYPE_LUAENTITY) {
  217. // Call parent's on_attach field
  218. m_env->getScriptIface()->luaentity_on_attach_child(parent_id, this);
  219. }
  220. }
  221. void UnitSAO::onDetach(int parent_id)
  222. {
  223. if (!parent_id)
  224. return;
  225. ServerActiveObject *parent = m_env->getActiveObject(parent_id);
  226. if (getType() == ACTIVEOBJECT_TYPE_LUAENTITY)
  227. m_env->getScriptIface()->luaentity_on_detach(m_id, parent);
  228. if (!parent || parent->isGone())
  229. return; // Do not try to notify soon gone parent
  230. if (parent->getType() == ACTIVEOBJECT_TYPE_LUAENTITY)
  231. m_env->getScriptIface()->luaentity_on_detach_child(parent_id, this);
  232. }
  233. ObjectProperties* UnitSAO::accessObjectProperties()
  234. {
  235. return &m_prop;
  236. }
  237. void UnitSAO::notifyObjectPropertiesModified()
  238. {
  239. m_properties_sent = false;
  240. }
  241. /*
  242. LuaEntitySAO
  243. */
  244. // Prototype (registers item for deserialization)
  245. LuaEntitySAO proto_LuaEntitySAO(NULL, v3f(0,0,0), "_prototype", "");
  246. LuaEntitySAO::LuaEntitySAO(ServerEnvironment *env, v3f pos,
  247. const std::string &name, const std::string &state):
  248. UnitSAO(env, pos),
  249. m_init_name(name),
  250. m_init_state(state)
  251. {
  252. // Only register type if no environment supplied
  253. if(env == NULL){
  254. ServerActiveObject::registerType(getType(), create);
  255. return;
  256. }
  257. }
  258. LuaEntitySAO::~LuaEntitySAO()
  259. {
  260. if(m_registered){
  261. m_env->getScriptIface()->luaentity_Remove(m_id);
  262. }
  263. for (u32 attached_particle_spawner : m_attached_particle_spawners) {
  264. m_env->deleteParticleSpawner(attached_particle_spawner, false);
  265. }
  266. }
  267. void LuaEntitySAO::addedToEnvironment(u32 dtime_s)
  268. {
  269. ServerActiveObject::addedToEnvironment(dtime_s);
  270. // Create entity from name
  271. m_registered = m_env->getScriptIface()->
  272. luaentity_Add(m_id, m_init_name.c_str());
  273. if(m_registered){
  274. // Get properties
  275. m_env->getScriptIface()->
  276. luaentity_GetProperties(m_id, this, &m_prop);
  277. // Initialize HP from properties
  278. m_hp = m_prop.hp_max;
  279. // Activate entity, supplying serialized state
  280. m_env->getScriptIface()->
  281. luaentity_Activate(m_id, m_init_state, dtime_s);
  282. } else {
  283. m_prop.infotext = m_init_name;
  284. }
  285. }
  286. ServerActiveObject* LuaEntitySAO::create(ServerEnvironment *env, v3f pos,
  287. const std::string &data)
  288. {
  289. std::string name;
  290. std::string state;
  291. u16 hp = 1;
  292. v3f velocity;
  293. v3f rotation;
  294. while (!data.empty()) { // breakable, run for one iteration
  295. std::istringstream is(data, std::ios::binary);
  296. // 'version' does not allow to incrementally extend the parameter list thus
  297. // we need another variable to build on top of 'version=1'. Ugly hack but works™
  298. u8 version2 = 0;
  299. u8 version = readU8(is);
  300. name = deSerializeString(is);
  301. state = deSerializeLongString(is);
  302. if (version < 1)
  303. break;
  304. hp = readU16(is);
  305. velocity = readV3F1000(is);
  306. // yaw must be yaw to be backwards-compatible
  307. rotation.Y = readF1000(is);
  308. if (is.good()) // EOF for old formats
  309. version2 = readU8(is);
  310. if (version2 < 1) // PROTOCOL_VERSION < 37
  311. break;
  312. // version2 >= 1
  313. rotation.X = readF1000(is);
  314. rotation.Z = readF1000(is);
  315. // if (version2 < 2)
  316. // break;
  317. // <read new values>
  318. break;
  319. }
  320. // create object
  321. infostream << "LuaEntitySAO::create(name=\"" << name << "\" state=\""
  322. << state << "\")" << std::endl;
  323. LuaEntitySAO *sao = new LuaEntitySAO(env, pos, name, state);
  324. sao->m_hp = hp;
  325. sao->m_velocity = velocity;
  326. sao->m_rotation = rotation;
  327. return sao;
  328. }
  329. void LuaEntitySAO::step(float dtime, bool send_recommended)
  330. {
  331. if(!m_properties_sent)
  332. {
  333. m_properties_sent = true;
  334. std::string str = getPropertyPacket();
  335. // create message and add to list
  336. ActiveObjectMessage aom(getId(), true, str);
  337. m_messages_out.push(aom);
  338. }
  339. // If attached, check that our parent is still there. If it isn't, detach.
  340. if(m_attachment_parent_id && !isAttached())
  341. {
  342. m_attachment_parent_id = 0;
  343. m_attachment_bone = "";
  344. m_attachment_position = v3f(0,0,0);
  345. m_attachment_rotation = v3f(0,0,0);
  346. sendPosition(false, true);
  347. }
  348. m_last_sent_position_timer += dtime;
  349. // Each frame, parent position is copied if the object is attached, otherwise it's calculated normally
  350. // If the object gets detached this comes into effect automatically from the last known origin
  351. if(isAttached())
  352. {
  353. v3f pos = m_env->getActiveObject(m_attachment_parent_id)->getBasePosition();
  354. m_base_position = pos;
  355. m_velocity = v3f(0,0,0);
  356. m_acceleration = v3f(0,0,0);
  357. }
  358. else
  359. {
  360. if(m_prop.physical){
  361. aabb3f box = m_prop.collisionbox;
  362. box.MinEdge *= BS;
  363. box.MaxEdge *= BS;
  364. collisionMoveResult moveresult;
  365. f32 pos_max_d = BS*0.25; // Distance per iteration
  366. v3f p_pos = m_base_position;
  367. v3f p_velocity = m_velocity;
  368. v3f p_acceleration = m_acceleration;
  369. moveresult = collisionMoveSimple(m_env, m_env->getGameDef(),
  370. pos_max_d, box, m_prop.stepheight, dtime,
  371. &p_pos, &p_velocity, p_acceleration,
  372. this, m_prop.collideWithObjects);
  373. // Apply results
  374. m_base_position = p_pos;
  375. m_velocity = p_velocity;
  376. m_acceleration = p_acceleration;
  377. } else {
  378. m_base_position += dtime * m_velocity + 0.5 * dtime
  379. * dtime * m_acceleration;
  380. m_velocity += dtime * m_acceleration;
  381. }
  382. if (m_prop.automatic_face_movement_dir &&
  383. (fabs(m_velocity.Z) > 0.001 || fabs(m_velocity.X) > 0.001)) {
  384. float target_yaw = atan2(m_velocity.Z, m_velocity.X) * 180 / M_PI
  385. + m_prop.automatic_face_movement_dir_offset;
  386. float max_rotation_per_sec =
  387. m_prop.automatic_face_movement_max_rotation_per_sec;
  388. if (max_rotation_per_sec > 0) {
  389. m_rotation.Y = wrapDegrees_0_360(m_rotation.Y);
  390. wrappedApproachShortest(m_rotation.Y, target_yaw,
  391. dtime * max_rotation_per_sec, 360.f);
  392. } else {
  393. // Negative values of max_rotation_per_sec mean disabled.
  394. m_rotation.Y = target_yaw;
  395. }
  396. }
  397. }
  398. if(m_registered){
  399. m_env->getScriptIface()->luaentity_Step(m_id, dtime);
  400. }
  401. if (!send_recommended)
  402. return;
  403. if(!isAttached())
  404. {
  405. // TODO: force send when acceleration changes enough?
  406. float minchange = 0.2*BS;
  407. if(m_last_sent_position_timer > 1.0){
  408. minchange = 0.01*BS;
  409. } else if(m_last_sent_position_timer > 0.2){
  410. minchange = 0.05*BS;
  411. }
  412. float move_d = m_base_position.getDistanceFrom(m_last_sent_position);
  413. move_d += m_last_sent_move_precision;
  414. float vel_d = m_velocity.getDistanceFrom(m_last_sent_velocity);
  415. if (move_d > minchange || vel_d > minchange ||
  416. std::fabs(m_rotation.X - m_last_sent_rotation.X) > 1.0f ||
  417. std::fabs(m_rotation.Y - m_last_sent_rotation.Y) > 1.0f ||
  418. std::fabs(m_rotation.Z - m_last_sent_rotation.Z) > 1.0f) {
  419. sendPosition(true, false);
  420. }
  421. }
  422. if (!m_armor_groups_sent) {
  423. m_armor_groups_sent = true;
  424. std::string str = gob_cmd_update_armor_groups(
  425. m_armor_groups);
  426. // create message and add to list
  427. ActiveObjectMessage aom(getId(), true, str);
  428. m_messages_out.push(aom);
  429. }
  430. if (!m_animation_sent) {
  431. m_animation_sent = true;
  432. std::string str = gob_cmd_update_animation(
  433. m_animation_range, m_animation_speed, m_animation_blend, m_animation_loop);
  434. // create message and add to list
  435. ActiveObjectMessage aom(getId(), true, str);
  436. m_messages_out.push(aom);
  437. }
  438. if (!m_animation_speed_sent) {
  439. m_animation_speed_sent = true;
  440. std::string str = gob_cmd_update_animation_speed(m_animation_speed);
  441. // create message and add to list
  442. ActiveObjectMessage aom(getId(), true, str);
  443. m_messages_out.push(aom);
  444. }
  445. if (!m_bone_position_sent) {
  446. m_bone_position_sent = true;
  447. for (std::unordered_map<std::string, core::vector2d<v3f>>::const_iterator
  448. ii = m_bone_position.begin(); ii != m_bone_position.end(); ++ii){
  449. std::string str = gob_cmd_update_bone_position((*ii).first,
  450. (*ii).second.X, (*ii).second.Y);
  451. // create message and add to list
  452. ActiveObjectMessage aom(getId(), true, str);
  453. m_messages_out.push(aom);
  454. }
  455. }
  456. if (!m_attachment_sent) {
  457. m_attachment_sent = true;
  458. std::string str = gob_cmd_update_attachment(m_attachment_parent_id, m_attachment_bone, m_attachment_position, m_attachment_rotation);
  459. // create message and add to list
  460. ActiveObjectMessage aom(getId(), true, str);
  461. m_messages_out.push(aom);
  462. }
  463. }
  464. std::string LuaEntitySAO::getClientInitializationData(u16 protocol_version)
  465. {
  466. std::ostringstream os(std::ios::binary);
  467. // PROTOCOL_VERSION >= 37
  468. writeU8(os, 1); // version
  469. os << serializeString(""); // name
  470. writeU8(os, 0); // is_player
  471. writeU16(os, getId()); //id
  472. writeV3F32(os, m_base_position);
  473. writeV3F32(os, m_rotation);
  474. writeU16(os, m_hp);
  475. std::ostringstream msg_os(std::ios::binary);
  476. msg_os << serializeLongString(getPropertyPacket()); // message 1
  477. msg_os << serializeLongString(gob_cmd_update_armor_groups(m_armor_groups)); // 2
  478. msg_os << serializeLongString(gob_cmd_update_animation(
  479. m_animation_range, m_animation_speed, m_animation_blend, m_animation_loop)); // 3
  480. for (std::unordered_map<std::string, core::vector2d<v3f>>::const_iterator
  481. ii = m_bone_position.begin(); ii != m_bone_position.end(); ++ii) {
  482. msg_os << serializeLongString(gob_cmd_update_bone_position((*ii).first,
  483. (*ii).second.X, (*ii).second.Y)); // m_bone_position.size
  484. }
  485. msg_os << serializeLongString(gob_cmd_update_attachment(m_attachment_parent_id,
  486. m_attachment_bone, m_attachment_position, m_attachment_rotation)); // 4
  487. int message_count = 4 + m_bone_position.size();
  488. for (std::unordered_set<int>::const_iterator ii = m_attachment_child_ids.begin();
  489. (ii != m_attachment_child_ids.end()); ++ii) {
  490. if (ServerActiveObject *obj = m_env->getActiveObject(*ii)) {
  491. message_count++;
  492. // TODO after a protocol bump: only send the object initialization data
  493. // to older clients (superfluous since this message exists)
  494. msg_os << serializeLongString(gob_cmd_update_infant(*ii, obj->getSendType(),
  495. obj->getClientInitializationData(protocol_version)));
  496. }
  497. }
  498. msg_os << serializeLongString(gob_cmd_set_texture_mod(m_current_texture_modifier));
  499. message_count++;
  500. writeU8(os, message_count);
  501. os.write(msg_os.str().c_str(), msg_os.str().size());
  502. // return result
  503. return os.str();
  504. }
  505. void LuaEntitySAO::getStaticData(std::string *result) const
  506. {
  507. verbosestream<<FUNCTION_NAME<<std::endl;
  508. std::ostringstream os(std::ios::binary);
  509. // version must be 1 to keep backwards-compatibility. See version2
  510. writeU8(os, 1);
  511. // name
  512. os<<serializeString(m_init_name);
  513. // state
  514. if(m_registered){
  515. std::string state = m_env->getScriptIface()->
  516. luaentity_GetStaticdata(m_id);
  517. os<<serializeLongString(state);
  518. } else {
  519. os<<serializeLongString(m_init_state);
  520. }
  521. writeU16(os, m_hp);
  522. writeV3F1000(os, m_velocity);
  523. // yaw
  524. writeF1000(os, m_rotation.Y);
  525. // version2. Increase this variable for new values
  526. writeU8(os, 1); // PROTOCOL_VERSION >= 37
  527. writeF1000(os, m_rotation.X);
  528. writeF1000(os, m_rotation.Z);
  529. // <write new values>
  530. *result = os.str();
  531. }
  532. u16 LuaEntitySAO::punch(v3f dir,
  533. const ToolCapabilities *toolcap,
  534. ServerActiveObject *puncher,
  535. float time_from_last_punch)
  536. {
  537. if (!m_registered) {
  538. // Delete unknown LuaEntities when punched
  539. m_pending_removal = true;
  540. return 0;
  541. }
  542. FATAL_ERROR_IF(!puncher, "Punch action called without SAO");
  543. s32 old_hp = getHP();
  544. ItemStack selected_item, hand_item;
  545. ItemStack tool_item = puncher->getWieldedItem(&selected_item, &hand_item);
  546. PunchDamageResult result = getPunchDamage(
  547. m_armor_groups,
  548. toolcap,
  549. &tool_item,
  550. time_from_last_punch);
  551. bool damage_handled = m_env->getScriptIface()->luaentity_Punch(m_id, puncher,
  552. time_from_last_punch, toolcap, dir, result.did_punch ? result.damage : 0);
  553. if (!damage_handled) {
  554. if (result.did_punch) {
  555. setHP((s32)getHP() - result.damage,
  556. PlayerHPChangeReason(PlayerHPChangeReason::SET_HP));
  557. std::string str = gob_cmd_punched(getHP());
  558. // create message and add to list
  559. ActiveObjectMessage aom(getId(), true, str);
  560. m_messages_out.push(aom);
  561. }
  562. }
  563. if (getHP() == 0 && !isGone()) {
  564. m_pending_removal = true;
  565. clearParentAttachment();
  566. clearChildAttachments();
  567. m_env->getScriptIface()->luaentity_on_death(m_id, puncher);
  568. }
  569. actionstream << puncher->getDescription() << " (id=" << puncher->getId() <<
  570. ", hp=" << puncher->getHP() << ") punched " <<
  571. getDescription() << " (id=" << m_id << ", hp=" << m_hp <<
  572. "), damage=" << (old_hp - (s32)getHP()) <<
  573. (damage_handled ? " (handled by Lua)" : "") << std::endl;
  574. return result.wear;
  575. }
  576. void LuaEntitySAO::rightClick(ServerActiveObject *clicker)
  577. {
  578. if (!m_registered)
  579. return;
  580. m_env->getScriptIface()->luaentity_Rightclick(m_id, clicker);
  581. }
  582. void LuaEntitySAO::setPos(const v3f &pos)
  583. {
  584. if(isAttached())
  585. return;
  586. m_base_position = pos;
  587. sendPosition(false, true);
  588. }
  589. void LuaEntitySAO::moveTo(v3f pos, bool continuous)
  590. {
  591. if(isAttached())
  592. return;
  593. m_base_position = pos;
  594. if(!continuous)
  595. sendPosition(true, true);
  596. }
  597. float LuaEntitySAO::getMinimumSavedMovement()
  598. {
  599. return 0.1 * BS;
  600. }
  601. std::string LuaEntitySAO::getDescription()
  602. {
  603. std::ostringstream os(std::ios::binary);
  604. os<<"LuaEntitySAO at (";
  605. os<<(m_base_position.X/BS)<<",";
  606. os<<(m_base_position.Y/BS)<<",";
  607. os<<(m_base_position.Z/BS);
  608. os<<")";
  609. return os.str();
  610. }
  611. void LuaEntitySAO::setHP(s32 hp, const PlayerHPChangeReason &reason)
  612. {
  613. m_hp = rangelim(hp, 0, U16_MAX);
  614. }
  615. u16 LuaEntitySAO::getHP() const
  616. {
  617. return m_hp;
  618. }
  619. void LuaEntitySAO::setVelocity(v3f velocity)
  620. {
  621. m_velocity = velocity;
  622. }
  623. v3f LuaEntitySAO::getVelocity()
  624. {
  625. return m_velocity;
  626. }
  627. void LuaEntitySAO::setAcceleration(v3f acceleration)
  628. {
  629. m_acceleration = acceleration;
  630. }
  631. v3f LuaEntitySAO::getAcceleration()
  632. {
  633. return m_acceleration;
  634. }
  635. void LuaEntitySAO::setTextureMod(const std::string &mod)
  636. {
  637. std::string str = gob_cmd_set_texture_mod(mod);
  638. m_current_texture_modifier = mod;
  639. // create message and add to list
  640. ActiveObjectMessage aom(getId(), true, str);
  641. m_messages_out.push(aom);
  642. }
  643. std::string LuaEntitySAO::getTextureMod() const
  644. {
  645. return m_current_texture_modifier;
  646. }
  647. void LuaEntitySAO::setSprite(v2s16 p, int num_frames, float framelength,
  648. bool select_horiz_by_yawpitch)
  649. {
  650. std::string str = gob_cmd_set_sprite(
  651. p,
  652. num_frames,
  653. framelength,
  654. select_horiz_by_yawpitch
  655. );
  656. // create message and add to list
  657. ActiveObjectMessage aom(getId(), true, str);
  658. m_messages_out.push(aom);
  659. }
  660. std::string LuaEntitySAO::getName()
  661. {
  662. return m_init_name;
  663. }
  664. std::string LuaEntitySAO::getPropertyPacket()
  665. {
  666. return gob_cmd_set_properties(m_prop);
  667. }
  668. void LuaEntitySAO::sendPosition(bool do_interpolate, bool is_movement_end)
  669. {
  670. // If the object is attached client-side, don't waste bandwidth sending its position to clients
  671. if(isAttached())
  672. return;
  673. m_last_sent_move_precision = m_base_position.getDistanceFrom(
  674. m_last_sent_position);
  675. m_last_sent_position_timer = 0;
  676. m_last_sent_position = m_base_position;
  677. m_last_sent_velocity = m_velocity;
  678. //m_last_sent_acceleration = m_acceleration;
  679. m_last_sent_rotation = m_rotation;
  680. float update_interval = m_env->getSendRecommendedInterval();
  681. std::string str = gob_cmd_update_position(
  682. m_base_position,
  683. m_velocity,
  684. m_acceleration,
  685. m_rotation,
  686. do_interpolate,
  687. is_movement_end,
  688. update_interval
  689. );
  690. // create message and add to list
  691. ActiveObjectMessage aom(getId(), false, str);
  692. m_messages_out.push(aom);
  693. }
  694. bool LuaEntitySAO::getCollisionBox(aabb3f *toset) const
  695. {
  696. if (m_prop.physical)
  697. {
  698. //update collision box
  699. toset->MinEdge = m_prop.collisionbox.MinEdge * BS;
  700. toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS;
  701. toset->MinEdge += m_base_position;
  702. toset->MaxEdge += m_base_position;
  703. return true;
  704. }
  705. return false;
  706. }
  707. bool LuaEntitySAO::getSelectionBox(aabb3f *toset) const
  708. {
  709. if (!m_prop.is_visible || !m_prop.pointable) {
  710. return false;
  711. }
  712. toset->MinEdge = m_prop.selectionbox.MinEdge * BS;
  713. toset->MaxEdge = m_prop.selectionbox.MaxEdge * BS;
  714. return true;
  715. }
  716. bool LuaEntitySAO::collideWithObjects() const
  717. {
  718. return m_prop.collideWithObjects;
  719. }
  720. /*
  721. PlayerSAO
  722. */
  723. // No prototype, PlayerSAO does not need to be deserialized
  724. PlayerSAO::PlayerSAO(ServerEnvironment *env_, RemotePlayer *player_, session_t peer_id_,
  725. bool is_singleplayer):
  726. UnitSAO(env_, v3f(0,0,0)),
  727. m_player(player_),
  728. m_peer_id(peer_id_),
  729. m_is_singleplayer(is_singleplayer)
  730. {
  731. assert(m_peer_id != 0); // pre-condition
  732. m_prop.hp_max = PLAYER_MAX_HP_DEFAULT;
  733. m_prop.breath_max = PLAYER_MAX_BREATH_DEFAULT;
  734. m_prop.physical = false;
  735. m_prop.weight = 75;
  736. m_prop.collisionbox = aabb3f(-0.3f, 0.0f, -0.3f, 0.3f, 1.77f, 0.3f);
  737. m_prop.selectionbox = aabb3f(-0.3f, 0.0f, -0.3f, 0.3f, 1.77f, 0.3f);
  738. m_prop.pointable = true;
  739. // Start of default appearance, this should be overwritten by Lua
  740. m_prop.visual = "upright_sprite";
  741. m_prop.visual_size = v3f(1, 2, 1);
  742. m_prop.textures.clear();
  743. m_prop.textures.emplace_back("player.png");
  744. m_prop.textures.emplace_back("player_back.png");
  745. m_prop.colors.clear();
  746. m_prop.colors.emplace_back(255, 255, 255, 255);
  747. m_prop.spritediv = v2s16(1,1);
  748. m_prop.eye_height = 1.625f;
  749. // End of default appearance
  750. m_prop.is_visible = true;
  751. m_prop.backface_culling = false;
  752. m_prop.makes_footstep_sound = true;
  753. m_prop.stepheight = PLAYER_DEFAULT_STEPHEIGHT * BS;
  754. m_hp = m_prop.hp_max;
  755. m_breath = m_prop.breath_max;
  756. // Disable zoom in survival mode using a value of 0
  757. m_prop.zoom_fov = g_settings->getBool("creative_mode") ? 15.0f : 0.0f;
  758. if (!g_settings->getBool("enable_damage"))
  759. m_armor_groups["immortal"] = 1;
  760. }
  761. void PlayerSAO::finalize(RemotePlayer *player, const std::set<std::string> &privs)
  762. {
  763. assert(player);
  764. m_player = player;
  765. m_privs = privs;
  766. }
  767. v3f PlayerSAO::getEyeOffset() const
  768. {
  769. return v3f(0, BS * m_prop.eye_height, 0);
  770. }
  771. std::string PlayerSAO::getDescription()
  772. {
  773. return std::string("player ") + m_player->getName();
  774. }
  775. // Called after id has been set and has been inserted in environment
  776. void PlayerSAO::addedToEnvironment(u32 dtime_s)
  777. {
  778. ServerActiveObject::addedToEnvironment(dtime_s);
  779. ServerActiveObject::setBasePosition(m_base_position);
  780. m_player->setPlayerSAO(this);
  781. m_player->setPeerId(m_peer_id);
  782. m_last_good_position = m_base_position;
  783. }
  784. // Called before removing from environment
  785. void PlayerSAO::removingFromEnvironment()
  786. {
  787. ServerActiveObject::removingFromEnvironment();
  788. if (m_player->getPlayerSAO() == this) {
  789. unlinkPlayerSessionAndSave();
  790. for (u32 attached_particle_spawner : m_attached_particle_spawners) {
  791. m_env->deleteParticleSpawner(attached_particle_spawner, false);
  792. }
  793. }
  794. }
  795. std::string PlayerSAO::getClientInitializationData(u16 protocol_version)
  796. {
  797. std::ostringstream os(std::ios::binary);
  798. // Protocol >= 15
  799. writeU8(os, 1); // version
  800. os << serializeString(m_player->getName()); // name
  801. writeU8(os, 1); // is_player
  802. writeS16(os, getId()); // id
  803. writeV3F32(os, m_base_position);
  804. writeV3F32(os, m_rotation);
  805. writeU16(os, getHP());
  806. std::ostringstream msg_os(std::ios::binary);
  807. msg_os << serializeLongString(getPropertyPacket()); // message 1
  808. msg_os << serializeLongString(gob_cmd_update_armor_groups(m_armor_groups)); // 2
  809. msg_os << serializeLongString(gob_cmd_update_animation(
  810. m_animation_range, m_animation_speed, m_animation_blend, m_animation_loop)); // 3
  811. for (std::unordered_map<std::string, core::vector2d<v3f>>::const_iterator
  812. ii = m_bone_position.begin(); ii != m_bone_position.end(); ++ii) {
  813. msg_os << serializeLongString(gob_cmd_update_bone_position((*ii).first,
  814. (*ii).second.X, (*ii).second.Y)); // m_bone_position.size
  815. }
  816. msg_os << serializeLongString(gob_cmd_update_attachment(m_attachment_parent_id,
  817. m_attachment_bone, m_attachment_position, m_attachment_rotation)); // 4
  818. msg_os << serializeLongString(gob_cmd_update_physics_override(m_physics_override_speed,
  819. m_physics_override_jump, m_physics_override_gravity, m_physics_override_sneak,
  820. m_physics_override_sneak_glitch, m_physics_override_new_move)); // 5
  821. // (GENERIC_CMD_UPDATE_NAMETAG_ATTRIBUTES) : Deprecated, for backwards compatibility only.
  822. msg_os << serializeLongString(gob_cmd_update_nametag_attributes(m_prop.nametag_color)); // 6
  823. int message_count = 6 + m_bone_position.size();
  824. for (std::unordered_set<int>::const_iterator ii = m_attachment_child_ids.begin();
  825. ii != m_attachment_child_ids.end(); ++ii) {
  826. if (ServerActiveObject *obj = m_env->getActiveObject(*ii)) {
  827. message_count++;
  828. msg_os << serializeLongString(gob_cmd_update_infant(*ii, obj->getSendType(),
  829. obj->getClientInitializationData(protocol_version)));
  830. }
  831. }
  832. writeU8(os, message_count);
  833. os.write(msg_os.str().c_str(), msg_os.str().size());
  834. // return result
  835. return os.str();
  836. }
  837. void PlayerSAO::getStaticData(std::string * result) const
  838. {
  839. FATAL_ERROR("Deprecated function");
  840. }
  841. void PlayerSAO::step(float dtime, bool send_recommended)
  842. {
  843. if (!isImmortal() && m_drowning_interval.step(dtime, 2.0f)) {
  844. // Get nose/mouth position, approximate with eye position
  845. v3s16 p = floatToInt(getEyePosition(), BS);
  846. MapNode n = m_env->getMap().getNode(p);
  847. const ContentFeatures &c = m_env->getGameDef()->ndef()->get(n);
  848. // If node generates drown
  849. if (c.drowning > 0 && m_hp > 0) {
  850. if (m_breath > 0)
  851. setBreath(m_breath - 1);
  852. // No more breath, damage player
  853. if (m_breath == 0) {
  854. PlayerHPChangeReason reason(PlayerHPChangeReason::DROWNING);
  855. setHP(m_hp - c.drowning, reason);
  856. m_env->getGameDef()->SendPlayerHPOrDie(this, reason);
  857. }
  858. }
  859. }
  860. if (m_breathing_interval.step(dtime, 0.5f) && !isImmortal()) {
  861. // Get nose/mouth position, approximate with eye position
  862. v3s16 p = floatToInt(getEyePosition(), BS);
  863. MapNode n = m_env->getMap().getNode(p);
  864. const ContentFeatures &c = m_env->getGameDef()->ndef()->get(n);
  865. // If player is alive & not drowning & not in ignore & not immortal, breathe
  866. if (m_breath < m_prop.breath_max && c.drowning == 0 &&
  867. n.getContent() != CONTENT_IGNORE && m_hp > 0)
  868. setBreath(m_breath + 1);
  869. }
  870. if (!isImmortal() && m_node_hurt_interval.step(dtime, 1.0f)) {
  871. u32 damage_per_second = 0;
  872. std::string nodename;
  873. // Lowest and highest damage points are 0.1 within collisionbox
  874. float dam_top = m_prop.collisionbox.MaxEdge.Y - 0.1f;
  875. // Sequence of damage points, starting 0.1 above feet and progressing
  876. // upwards in 1 node intervals, stopping below top damage point.
  877. for (float dam_height = 0.1f; dam_height < dam_top; dam_height++) {
  878. v3s16 p = floatToInt(m_base_position +
  879. v3f(0.0f, dam_height * BS, 0.0f), BS);
  880. MapNode n = m_env->getMap().getNode(p);
  881. const ContentFeatures &c = m_env->getGameDef()->ndef()->get(n);
  882. if (c.damage_per_second > damage_per_second) {
  883. damage_per_second = c.damage_per_second;
  884. nodename = c.name;
  885. }
  886. }
  887. // Top damage point
  888. v3s16 ptop = floatToInt(m_base_position +
  889. v3f(0.0f, dam_top * BS, 0.0f), BS);
  890. MapNode ntop = m_env->getMap().getNode(ptop);
  891. const ContentFeatures &c = m_env->getGameDef()->ndef()->get(ntop);
  892. if (c.damage_per_second > damage_per_second) {
  893. damage_per_second = c.damage_per_second;
  894. nodename = c.name;
  895. }
  896. if (damage_per_second != 0 && m_hp > 0) {
  897. s32 newhp = (s32)m_hp - (s32)damage_per_second;
  898. PlayerHPChangeReason reason(PlayerHPChangeReason::NODE_DAMAGE, nodename);
  899. setHP(newhp, reason);
  900. m_env->getGameDef()->SendPlayerHPOrDie(this, reason);
  901. }
  902. }
  903. if (!m_properties_sent) {
  904. m_properties_sent = true;
  905. std::string str = getPropertyPacket();
  906. // create message and add to list
  907. ActiveObjectMessage aom(getId(), true, str);
  908. m_messages_out.push(aom);
  909. m_env->getScriptIface()->player_event(this, "properties_changed");
  910. }
  911. // If attached, check that our parent is still there. If it isn't, detach.
  912. if (m_attachment_parent_id && !isAttached()) {
  913. m_attachment_parent_id = 0;
  914. m_attachment_bone = "";
  915. m_attachment_position = v3f(0.0f, 0.0f, 0.0f);
  916. m_attachment_rotation = v3f(0.0f, 0.0f, 0.0f);
  917. setBasePosition(m_last_good_position);
  918. m_env->getGameDef()->SendMovePlayer(m_peer_id);
  919. }
  920. //dstream<<"PlayerSAO::step: dtime: "<<dtime<<std::endl;
  921. // Set lag pool maximums based on estimated lag
  922. const float LAG_POOL_MIN = 5.0f;
  923. float lag_pool_max = m_env->getMaxLagEstimate() * 2.0f;
  924. if(lag_pool_max < LAG_POOL_MIN)
  925. lag_pool_max = LAG_POOL_MIN;
  926. m_dig_pool.setMax(lag_pool_max);
  927. m_move_pool.setMax(lag_pool_max);
  928. // Increment cheat prevention timers
  929. m_dig_pool.add(dtime);
  930. m_move_pool.add(dtime);
  931. m_time_from_last_teleport += dtime;
  932. m_time_from_last_punch += dtime;
  933. m_nocheat_dig_time += dtime;
  934. m_max_speed_override_time = MYMAX(m_max_speed_override_time - dtime, 0.0f);
  935. // Each frame, parent position is copied if the object is attached,
  936. // otherwise it's calculated normally.
  937. // If the object gets detached this comes into effect automatically from
  938. // the last known origin.
  939. if (isAttached()) {
  940. v3f pos = m_env->getActiveObject(m_attachment_parent_id)->getBasePosition();
  941. m_last_good_position = pos;
  942. setBasePosition(pos);
  943. }
  944. if (!send_recommended)
  945. return;
  946. // If the object is attached client-side, don't waste bandwidth sending its
  947. // position or rotation to clients.
  948. if (m_position_not_sent && !isAttached()) {
  949. m_position_not_sent = false;
  950. float update_interval = m_env->getSendRecommendedInterval();
  951. v3f pos;
  952. if (isAttached()) // Just in case we ever do send attachment position too
  953. pos = m_env->getActiveObject(m_attachment_parent_id)->getBasePosition();
  954. else
  955. pos = m_base_position;
  956. std::string str = gob_cmd_update_position(
  957. pos,
  958. v3f(0.0f, 0.0f, 0.0f),
  959. v3f(0.0f, 0.0f, 0.0f),
  960. m_rotation,
  961. true,
  962. false,
  963. update_interval
  964. );
  965. // create message and add to list
  966. ActiveObjectMessage aom(getId(), false, str);
  967. m_messages_out.push(aom);
  968. }
  969. if (!m_armor_groups_sent) {
  970. m_armor_groups_sent = true;
  971. std::string str = gob_cmd_update_armor_groups(
  972. m_armor_groups);
  973. // create message and add to list
  974. ActiveObjectMessage aom(getId(), true, str);
  975. m_messages_out.push(aom);
  976. }
  977. if (!m_physics_override_sent) {
  978. m_physics_override_sent = true;
  979. std::string str = gob_cmd_update_physics_override(m_physics_override_speed,
  980. m_physics_override_jump, m_physics_override_gravity,
  981. m_physics_override_sneak, m_physics_override_sneak_glitch,
  982. m_physics_override_new_move);
  983. // create message and add to list
  984. ActiveObjectMessage aom(getId(), true, str);
  985. m_messages_out.push(aom);
  986. }
  987. if (!m_animation_sent) {
  988. m_animation_sent = true;
  989. std::string str = gob_cmd_update_animation(
  990. m_animation_range, m_animation_speed, m_animation_blend, m_animation_loop);
  991. // create message and add to list
  992. ActiveObjectMessage aom(getId(), true, str);
  993. m_messages_out.push(aom);
  994. }
  995. if (!m_bone_position_sent) {
  996. m_bone_position_sent = true;
  997. for (std::unordered_map<std::string, core::vector2d<v3f>>::const_iterator
  998. ii = m_bone_position.begin(); ii != m_bone_position.end(); ++ii) {
  999. std::string str = gob_cmd_update_bone_position((*ii).first,
  1000. (*ii).second.X, (*ii).second.Y);
  1001. // create message and add to list
  1002. ActiveObjectMessage aom(getId(), true, str);
  1003. m_messages_out.push(aom);
  1004. }
  1005. }
  1006. if (!m_attachment_sent) {
  1007. m_attachment_sent = true;
  1008. std::string str = gob_cmd_update_attachment(m_attachment_parent_id,
  1009. m_attachment_bone, m_attachment_position, m_attachment_rotation);
  1010. // create message and add to list
  1011. ActiveObjectMessage aom(getId(), true, str);
  1012. m_messages_out.push(aom);
  1013. }
  1014. }
  1015. void PlayerSAO::setBasePosition(const v3f &position)
  1016. {
  1017. if (m_player && position != m_base_position)
  1018. m_player->setDirty(true);
  1019. // This needs to be ran for attachments too
  1020. ServerActiveObject::setBasePosition(position);
  1021. // Updating is not wanted/required for player migration
  1022. if (m_env) {
  1023. m_position_not_sent = true;
  1024. }
  1025. }
  1026. void PlayerSAO::setPos(const v3f &pos)
  1027. {
  1028. if(isAttached())
  1029. return;
  1030. // Send mapblock of target location
  1031. v3s16 blockpos = v3s16(pos.X / MAP_BLOCKSIZE, pos.Y / MAP_BLOCKSIZE, pos.Z / MAP_BLOCKSIZE);
  1032. m_env->getGameDef()->SendBlock(m_peer_id, blockpos);
  1033. setBasePosition(pos);
  1034. // Movement caused by this command is always valid
  1035. m_last_good_position = pos;
  1036. m_move_pool.empty();
  1037. m_time_from_last_teleport = 0.0;
  1038. m_env->getGameDef()->SendMovePlayer(m_peer_id);
  1039. }
  1040. void PlayerSAO::moveTo(v3f pos, bool continuous)
  1041. {
  1042. if(isAttached())
  1043. return;
  1044. setBasePosition(pos);
  1045. // Movement caused by this command is always valid
  1046. m_last_good_position = pos;
  1047. m_move_pool.empty();
  1048. m_time_from_last_teleport = 0.0;
  1049. m_env->getGameDef()->SendMovePlayer(m_peer_id);
  1050. }
  1051. void PlayerSAO::setPlayerYaw(const float yaw)
  1052. {
  1053. v3f rotation(0, yaw, 0);
  1054. if (m_player && yaw != m_rotation.Y)
  1055. m_player->setDirty(true);
  1056. // Set player model yaw, not look view
  1057. UnitSAO::setRotation(rotation);
  1058. }
  1059. void PlayerSAO::setFov(const float fov)
  1060. {
  1061. if (m_player && fov != m_fov)
  1062. m_player->setDirty(true);
  1063. m_fov = fov;
  1064. }
  1065. void PlayerSAO::setWantedRange(const s16 range)
  1066. {
  1067. if (m_player && range != m_wanted_range)
  1068. m_player->setDirty(true);
  1069. m_wanted_range = range;
  1070. }
  1071. void PlayerSAO::setPlayerYawAndSend(const float yaw)
  1072. {
  1073. setPlayerYaw(yaw);
  1074. m_env->getGameDef()->SendMovePlayer(m_peer_id);
  1075. }
  1076. void PlayerSAO::setLookPitch(const float pitch)
  1077. {
  1078. if (m_player && pitch != m_pitch)
  1079. m_player->setDirty(true);
  1080. m_pitch = pitch;
  1081. }
  1082. void PlayerSAO::setLookPitchAndSend(const float pitch)
  1083. {
  1084. setLookPitch(pitch);
  1085. m_env->getGameDef()->SendMovePlayer(m_peer_id);
  1086. }
  1087. u16 PlayerSAO::punch(v3f dir,
  1088. const ToolCapabilities *toolcap,
  1089. ServerActiveObject *puncher,
  1090. float time_from_last_punch)
  1091. {
  1092. if (!toolcap)
  1093. return 0;
  1094. FATAL_ERROR_IF(!puncher, "Punch action called without SAO");
  1095. // No effect if PvP disabled or if immortal
  1096. if (isImmortal() || !g_settings->getBool("enable_pvp")) {
  1097. if (puncher->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
  1098. std::string str = gob_cmd_punched(getHP());
  1099. // create message and add to list
  1100. ActiveObjectMessage aom(getId(), true, str);
  1101. m_messages_out.push(aom);
  1102. return 0;
  1103. }
  1104. }
  1105. s32 old_hp = getHP();
  1106. HitParams hitparams = getHitParams(m_armor_groups, toolcap,
  1107. time_from_last_punch);
  1108. PlayerSAO *playersao = m_player->getPlayerSAO();
  1109. bool damage_handled = m_env->getScriptIface()->on_punchplayer(playersao,
  1110. puncher, time_from_last_punch, toolcap, dir,
  1111. hitparams.hp);
  1112. if (!damage_handled) {
  1113. setHP((s32)getHP() - (s32)hitparams.hp,
  1114. PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, puncher));
  1115. } else { // override client prediction
  1116. if (puncher->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
  1117. std::string str = gob_cmd_punched(getHP());
  1118. // create message and add to list
  1119. ActiveObjectMessage aom(getId(), true, str);
  1120. m_messages_out.push(aom);
  1121. }
  1122. }
  1123. actionstream << puncher->getDescription() << " (id=" << puncher->getId() <<
  1124. ", hp=" << puncher->getHP() << ") punched " <<
  1125. getDescription() << " (id=" << m_id << ", hp=" << m_hp <<
  1126. "), damage=" << (old_hp - (s32)getHP()) <<
  1127. (damage_handled ? " (handled by Lua)" : "") << std::endl;
  1128. return hitparams.wear;
  1129. }
  1130. void PlayerSAO::setHP(s32 hp, const PlayerHPChangeReason &reason)
  1131. {
  1132. s32 oldhp = m_hp;
  1133. hp = rangelim(hp, 0, m_prop.hp_max);
  1134. if (oldhp != hp) {
  1135. s32 hp_change = m_env->getScriptIface()->on_player_hpchange(this, hp - oldhp, reason);
  1136. if (hp_change == 0)
  1137. return;
  1138. hp = rangelim(oldhp + hp_change, 0, m_prop.hp_max);
  1139. }
  1140. if (hp < oldhp && isImmortal())
  1141. return;
  1142. m_hp = hp;
  1143. // Update properties on death
  1144. if ((hp == 0) != (oldhp == 0))
  1145. m_properties_sent = false;
  1146. }
  1147. void PlayerSAO::setBreath(const u16 breath, bool send)
  1148. {
  1149. if (m_player && breath != m_breath)
  1150. m_player->setDirty(true);
  1151. m_breath = rangelim(breath, 0, m_prop.breath_max);
  1152. if (send)
  1153. m_env->getGameDef()->SendPlayerBreath(this);
  1154. }
  1155. Inventory *PlayerSAO::getInventory() const
  1156. {
  1157. return m_player ? &m_player->inventory : nullptr;
  1158. }
  1159. InventoryLocation PlayerSAO::getInventoryLocation() const
  1160. {
  1161. InventoryLocation loc;
  1162. loc.setPlayer(m_player->getName());
  1163. return loc;
  1164. }
  1165. u16 PlayerSAO::getWieldIndex() const
  1166. {
  1167. return m_player->getWieldIndex();
  1168. }
  1169. ItemStack PlayerSAO::getWieldedItem(ItemStack *selected, ItemStack *hand) const
  1170. {
  1171. return m_player->getWieldedItem(selected, hand);
  1172. }
  1173. bool PlayerSAO::setWieldedItem(const ItemStack &item)
  1174. {
  1175. InventoryList *mlist = m_player->inventory.getList(getWieldList());
  1176. if (mlist) {
  1177. mlist->changeItem(m_player->getWieldIndex(), item);
  1178. return true;
  1179. }
  1180. return false;
  1181. }
  1182. void PlayerSAO::disconnected()
  1183. {
  1184. m_peer_id = 0;
  1185. m_pending_removal = true;
  1186. }
  1187. void PlayerSAO::unlinkPlayerSessionAndSave()
  1188. {
  1189. assert(m_player->getPlayerSAO() == this);
  1190. m_player->setPeerId(PEER_ID_INEXISTENT);
  1191. m_env->savePlayer(m_player);
  1192. m_player->setPlayerSAO(NULL);
  1193. m_env->removePlayer(m_player);
  1194. }
  1195. std::string PlayerSAO::getPropertyPacket()
  1196. {
  1197. m_prop.is_visible = (true);
  1198. return gob_cmd_set_properties(m_prop);
  1199. }
  1200. void PlayerSAO::setMaxSpeedOverride(const v3f &vel)
  1201. {
  1202. if (m_max_speed_override_time == 0.0f)
  1203. m_max_speed_override = vel;
  1204. else
  1205. m_max_speed_override += vel;
  1206. if (m_player) {
  1207. float accel = MYMIN(m_player->movement_acceleration_default,
  1208. m_player->movement_acceleration_air);
  1209. m_max_speed_override_time = m_max_speed_override.getLength() / accel / BS;
  1210. }
  1211. }
  1212. bool PlayerSAO::checkMovementCheat()
  1213. {
  1214. if (isAttached() || m_is_singleplayer ||
  1215. g_settings->getBool("disable_anticheat")) {
  1216. m_last_good_position = m_base_position;
  1217. return false;
  1218. }
  1219. bool cheated = false;
  1220. /*
  1221. Check player movements
  1222. NOTE: Actually the server should handle player physics like the
  1223. client does and compare player's position to what is calculated
  1224. on our side. This is required when eg. players fly due to an
  1225. explosion. Altough a node-based alternative might be possible
  1226. too, and much more lightweight.
  1227. */
  1228. float override_max_H, override_max_V;
  1229. if (m_max_speed_override_time > 0.0f) {
  1230. override_max_H = MYMAX(fabs(m_max_speed_override.X), fabs(m_max_speed_override.Z));
  1231. override_max_V = fabs(m_max_speed_override.Y);
  1232. } else {
  1233. override_max_H = override_max_V = 0.0f;
  1234. }
  1235. float player_max_walk = 0; // horizontal movement
  1236. float player_max_jump = 0; // vertical upwards movement
  1237. if (m_privs.count("fast") != 0)
  1238. player_max_walk = m_player->movement_speed_fast; // Fast speed
  1239. else
  1240. player_max_walk = m_player->movement_speed_walk; // Normal speed
  1241. player_max_walk *= m_physics_override_speed;
  1242. player_max_walk = MYMAX(player_max_walk, override_max_H);
  1243. player_max_jump = m_player->movement_speed_jump * m_physics_override_jump;
  1244. // FIXME: Bouncy nodes cause practically unbound increase in Y speed,
  1245. // until this can be verified correctly, tolerate higher jumping speeds
  1246. player_max_jump *= 2.0;
  1247. player_max_jump = MYMAX(player_max_jump, override_max_V);
  1248. // Don't divide by zero!
  1249. if (player_max_walk < 0.0001f)
  1250. player_max_walk = 0.0001f;
  1251. if (player_max_jump < 0.0001f)
  1252. player_max_jump = 0.0001f;
  1253. v3f diff = (m_base_position - m_last_good_position);
  1254. float d_vert = diff.Y;
  1255. diff.Y = 0;
  1256. float d_horiz = diff.getLength();
  1257. float required_time = d_horiz / player_max_walk;
  1258. // FIXME: Checking downwards movement is not easily possible currently,
  1259. // the server could calculate speed differences to examine the gravity
  1260. if (d_vert > 0) {
  1261. // In certain cases (water, ladders) walking speed is applied vertically
  1262. float s = MYMAX(player_max_jump, player_max_walk);
  1263. required_time = MYMAX(required_time, d_vert / s);
  1264. }
  1265. if (m_move_pool.grab(required_time)) {
  1266. m_last_good_position = m_base_position;
  1267. } else {
  1268. const float LAG_POOL_MIN = 5.0;
  1269. float lag_pool_max = m_env->getMaxLagEstimate() * 2.0;
  1270. lag_pool_max = MYMAX(lag_pool_max, LAG_POOL_MIN);
  1271. if (m_time_from_last_teleport > lag_pool_max) {
  1272. actionstream << "Player " << m_player->getName()
  1273. << " moved too fast; resetting position"
  1274. << std::endl;
  1275. cheated = true;
  1276. }
  1277. setBasePosition(m_last_good_position);
  1278. }
  1279. return cheated;
  1280. }
  1281. bool PlayerSAO::getCollisionBox(aabb3f *toset) const
  1282. {
  1283. //update collision box
  1284. toset->MinEdge = m_prop.collisionbox.MinEdge * BS;
  1285. toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS;
  1286. toset->MinEdge += m_base_position;
  1287. toset->MaxEdge += m_base_position;
  1288. return true;
  1289. }
  1290. bool PlayerSAO::getSelectionBox(aabb3f *toset) const
  1291. {
  1292. if (!m_prop.is_visible || !m_prop.pointable) {
  1293. return false;
  1294. }
  1295. toset->MinEdge = m_prop.selectionbox.MinEdge * BS;
  1296. toset->MaxEdge = m_prop.selectionbox.MaxEdge * BS;
  1297. return true;
  1298. }
  1299. float PlayerSAO::getZoomFOV() const
  1300. {
  1301. return m_prop.zoom_fov;
  1302. }