luaentity_sao.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. /*
  2. Minetest
  3. Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. Copyright (C) 2013-2020 Minetest core developers & community
  5. This program is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU Lesser General Public License as published by
  7. the Free Software Foundation; either version 2.1 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU Lesser General Public License for more details.
  13. You should have received a copy of the GNU Lesser General Public License along
  14. with this program; if not, write to the Free Software Foundation, Inc.,
  15. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  16. */
  17. #include "luaentity_sao.h"
  18. #include "collision.h"
  19. #include "constants.h"
  20. #include "inventory.h"
  21. #include "irrlicht_changes/printing.h"
  22. #include "player_sao.h"
  23. #include "scripting_server.h"
  24. #include "server.h"
  25. #include "serverenvironment.h"
  26. LuaEntitySAO::LuaEntitySAO(ServerEnvironment *env, v3f pos, const std::string &data)
  27. : UnitSAO(env, pos)
  28. {
  29. std::string name;
  30. std::string state;
  31. u16 hp = 1;
  32. v3f velocity;
  33. v3f rotation;
  34. while (!data.empty()) { // breakable, run for one iteration
  35. std::istringstream is(data, std::ios::binary);
  36. // 'version' does not allow to incrementally extend the parameter list thus
  37. // we need another variable to build on top of 'version=1'. Ugly hack but works™
  38. u8 version2 = 0;
  39. u8 version = readU8(is);
  40. name = deSerializeString16(is);
  41. state = deSerializeString32(is);
  42. if (version < 1)
  43. break;
  44. hp = readU16(is);
  45. velocity = readV3F1000(is);
  46. // yaw must be yaw to be backwards-compatible
  47. rotation.Y = readF1000(is);
  48. if (is.good()) // EOF for old formats
  49. version2 = readU8(is);
  50. if (version2 < 1) // PROTOCOL_VERSION < 37
  51. break;
  52. // version2 >= 1
  53. rotation.X = readF1000(is);
  54. rotation.Z = readF1000(is);
  55. // if (version2 < 2)
  56. // break;
  57. // <read new values>
  58. break;
  59. }
  60. // create object
  61. infostream << "LuaEntitySAO::create(name=\"" << name << "\" state is";
  62. if (state.empty())
  63. infostream << "empty";
  64. else
  65. infostream << state.size() << " bytes";
  66. infostream << ")" << std::endl;
  67. m_init_name = name;
  68. m_init_state = state;
  69. m_hp = hp;
  70. m_velocity = velocity;
  71. m_rotation = rotation;
  72. }
  73. LuaEntitySAO::~LuaEntitySAO()
  74. {
  75. if(m_registered){
  76. m_env->getScriptIface()->luaentity_Remove(m_id);
  77. }
  78. for (u32 attached_particle_spawner : m_attached_particle_spawners) {
  79. m_env->deleteParticleSpawner(attached_particle_spawner, false);
  80. }
  81. }
  82. void LuaEntitySAO::addedToEnvironment(u32 dtime_s)
  83. {
  84. ServerActiveObject::addedToEnvironment(dtime_s);
  85. // Create entity from name
  86. m_registered = m_env->getScriptIface()->
  87. luaentity_Add(m_id, m_init_name.c_str());
  88. if(m_registered){
  89. // Get properties
  90. m_env->getScriptIface()->
  91. luaentity_GetProperties(m_id, this, &m_prop, m_init_name);
  92. // Initialize HP from properties
  93. m_hp = m_prop.hp_max;
  94. // Activate entity, supplying serialized state
  95. m_env->getScriptIface()->
  96. luaentity_Activate(m_id, m_init_state, dtime_s);
  97. } else {
  98. // It's an unknown object
  99. // Use entitystring as infotext for debugging
  100. m_prop.infotext = m_init_name;
  101. // Set unknown object texture
  102. m_prop.textures.clear();
  103. m_prop.textures.emplace_back("unknown_object.png");
  104. }
  105. }
  106. void LuaEntitySAO::dispatchScriptDeactivate(bool removal)
  107. {
  108. // Ensure that this is in fact a registered entity,
  109. // and that it isn't already gone.
  110. // The latter also prevents this from ever being called twice.
  111. if (m_registered && !isGone())
  112. m_env->getScriptIface()->luaentity_Deactivate(m_id, removal);
  113. }
  114. void LuaEntitySAO::step(float dtime, bool send_recommended)
  115. {
  116. if(!m_properties_sent)
  117. {
  118. m_properties_sent = true;
  119. std::string str = getPropertyPacket();
  120. // create message and add to list
  121. m_messages_out.emplace(getId(), true, str);
  122. }
  123. // If attached, check that our parent is still there. If it isn't, detach.
  124. if (m_attachment_parent_id && !isAttached()) {
  125. // This is handled when objects are removed from the map
  126. warningstream << "LuaEntitySAO::step() " << m_init_name << " at " << m_last_sent_position << ", id=" << m_id <<
  127. " is attached to nonexistent parent. This is a bug." << std::endl;
  128. clearParentAttachment();
  129. sendPosition(false, true);
  130. }
  131. m_last_sent_position_timer += dtime;
  132. collisionMoveResult moveresult, *moveresult_p = nullptr;
  133. // Each frame, parent position is copied if the object is attached, otherwise it's calculated normally
  134. // If the object gets detached this comes into effect automatically from the last known origin
  135. if (auto *parent = getParent()) {
  136. m_base_position = parent->getBasePosition();
  137. m_velocity = v3f(0,0,0);
  138. m_acceleration = v3f(0,0,0);
  139. } else {
  140. if(m_prop.physical){
  141. aabb3f box = m_prop.collisionbox;
  142. box.MinEdge *= BS;
  143. box.MaxEdge *= BS;
  144. f32 pos_max_d = BS*0.25; // Distance per iteration
  145. v3f p_pos = m_base_position;
  146. v3f p_velocity = m_velocity;
  147. v3f p_acceleration = m_acceleration;
  148. moveresult = collisionMoveSimple(m_env, m_env->getGameDef(),
  149. pos_max_d, box, m_prop.stepheight, dtime,
  150. &p_pos, &p_velocity, p_acceleration,
  151. this, m_prop.collideWithObjects);
  152. moveresult_p = &moveresult;
  153. // Apply results
  154. m_base_position = p_pos;
  155. m_velocity = p_velocity;
  156. m_acceleration = p_acceleration;
  157. } else {
  158. m_base_position += (m_velocity + m_acceleration * 0.5f * dtime) * dtime;
  159. m_velocity += dtime * m_acceleration;
  160. }
  161. if (m_prop.automatic_face_movement_dir &&
  162. (fabs(m_velocity.Z) > 0.001 || fabs(m_velocity.X) > 0.001)) {
  163. float target_yaw = atan2(m_velocity.Z, m_velocity.X) * 180 / M_PI
  164. + m_prop.automatic_face_movement_dir_offset;
  165. float max_rotation_per_sec =
  166. m_prop.automatic_face_movement_max_rotation_per_sec;
  167. if (max_rotation_per_sec > 0) {
  168. m_rotation.Y = wrapDegrees_0_360(m_rotation.Y);
  169. wrappedApproachShortest(m_rotation.Y, target_yaw,
  170. dtime * max_rotation_per_sec, 360.f);
  171. } else {
  172. // Negative values of max_rotation_per_sec mean disabled.
  173. m_rotation.Y = target_yaw;
  174. }
  175. }
  176. }
  177. if (std::abs(m_prop.automatic_rotate) > 0.001f) {
  178. m_rotation_add_yaw = modulo360f(m_rotation_add_yaw + dtime * core::RADTODEG *
  179. m_prop.automatic_rotate);
  180. }
  181. if(m_registered) {
  182. m_env->getScriptIface()->luaentity_Step(m_id, dtime, moveresult_p);
  183. }
  184. if (!send_recommended)
  185. return;
  186. if(!isAttached())
  187. {
  188. // TODO: force send when acceleration changes enough?
  189. float minchange = 0.2*BS;
  190. if(m_last_sent_position_timer > 1.0){
  191. minchange = 0.01*BS;
  192. } else if(m_last_sent_position_timer > 0.2){
  193. minchange = 0.05*BS;
  194. }
  195. float move_d = m_base_position.getDistanceFrom(m_last_sent_position);
  196. move_d += m_last_sent_move_precision;
  197. float vel_d = m_velocity.getDistanceFrom(m_last_sent_velocity);
  198. if (move_d > minchange || vel_d > minchange ||
  199. std::fabs(m_rotation.X - m_last_sent_rotation.X) > 1.0f ||
  200. std::fabs(m_rotation.Y - m_last_sent_rotation.Y) > 1.0f ||
  201. std::fabs(m_rotation.Z - m_last_sent_rotation.Z) > 1.0f) {
  202. sendPosition(true, false);
  203. }
  204. }
  205. sendOutdatedData();
  206. }
  207. std::string LuaEntitySAO::getClientInitializationData(u16 protocol_version)
  208. {
  209. std::ostringstream os(std::ios::binary);
  210. // PROTOCOL_VERSION >= 37
  211. writeU8(os, 1); // version
  212. os << serializeString16(m_init_name); // name
  213. writeU8(os, 0); // is_player
  214. writeU16(os, getId()); //id
  215. writeV3F32(os, m_base_position);
  216. writeV3F32(os, m_rotation);
  217. writeU16(os, m_hp);
  218. std::ostringstream msg_os(std::ios::binary);
  219. msg_os << serializeString32(getPropertyPacket()); // message 1
  220. msg_os << serializeString32(generateUpdateArmorGroupsCommand()); // 2
  221. msg_os << serializeString32(generateUpdateAnimationCommand()); // 3
  222. for (const auto &bone_override : m_bone_override) {
  223. msg_os << serializeString32(generateUpdateBoneOverrideCommand(
  224. bone_override.first, bone_override.second)); // 3 + N
  225. }
  226. msg_os << serializeString32(generateUpdateAttachmentCommand()); // 4 + m_bone_override.size
  227. int message_count = 4 + m_bone_override.size();
  228. for (const auto &id : getAttachmentChildIds()) {
  229. if (ServerActiveObject *obj = m_env->getActiveObject(id)) {
  230. message_count++;
  231. msg_os << serializeString32(obj->generateUpdateInfantCommand(
  232. id, protocol_version));
  233. }
  234. }
  235. msg_os << serializeString32(generateSetTextureModCommand());
  236. message_count++;
  237. writeU8(os, message_count);
  238. std::string serialized = msg_os.str();
  239. os.write(serialized.c_str(), serialized.size());
  240. // return result
  241. return os.str();
  242. }
  243. void LuaEntitySAO::getStaticData(std::string *result) const
  244. {
  245. std::ostringstream os(std::ios::binary);
  246. // version must be 1 to keep backwards-compatibility. See version2
  247. writeU8(os, 1);
  248. // name
  249. os<<serializeString16(m_init_name);
  250. // state
  251. if(m_registered){
  252. std::string state = m_env->getScriptIface()->
  253. luaentity_GetStaticdata(m_id);
  254. os<<serializeString32(state);
  255. } else {
  256. os<<serializeString32(m_init_state);
  257. }
  258. writeU16(os, m_hp);
  259. writeV3F1000(os, clampToF1000(m_velocity));
  260. // yaw
  261. writeF1000(os, m_rotation.Y);
  262. // version2. Increase this variable for new values
  263. writeU8(os, 1); // PROTOCOL_VERSION >= 37
  264. writeF1000(os, m_rotation.X);
  265. writeF1000(os, m_rotation.Z);
  266. // <write new values>
  267. *result = os.str();
  268. }
  269. u32 LuaEntitySAO::punch(v3f dir,
  270. const ToolCapabilities *toolcap,
  271. ServerActiveObject *puncher,
  272. float time_from_last_punch,
  273. u16 initial_wear)
  274. {
  275. if (!m_registered) {
  276. // Delete unknown LuaEntities when punched
  277. markForRemoval();
  278. return 0;
  279. }
  280. FATAL_ERROR_IF(!puncher, "Punch action called without SAO");
  281. s32 old_hp = getHP();
  282. ItemStack selected_item, hand_item;
  283. ItemStack tool_item = puncher->getWieldedItem(&selected_item, &hand_item);
  284. PunchDamageResult result = getPunchDamage(
  285. m_armor_groups,
  286. toolcap,
  287. &tool_item,
  288. time_from_last_punch,
  289. initial_wear);
  290. bool damage_handled = m_env->getScriptIface()->luaentity_Punch(m_id, puncher,
  291. time_from_last_punch, toolcap, dir, result.did_punch ? result.damage : 0);
  292. if (!damage_handled) {
  293. if (result.did_punch) {
  294. setHP((s32)getHP() - result.damage,
  295. PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, puncher));
  296. }
  297. }
  298. actionstream << puncher->getDescription() << " (id=" << puncher->getId() <<
  299. ", hp=" << puncher->getHP() << ") punched " <<
  300. getDescription() << " (id=" << m_id << ", hp=" << m_hp <<
  301. "), damage=" << (old_hp - (s32)getHP()) <<
  302. (damage_handled ? " (handled by Lua)" : "") << std::endl;
  303. // TODO: give Lua control over wear
  304. return result.wear;
  305. }
  306. void LuaEntitySAO::rightClick(ServerActiveObject *clicker)
  307. {
  308. if (!m_registered)
  309. return;
  310. m_env->getScriptIface()->luaentity_Rightclick(m_id, clicker);
  311. }
  312. void LuaEntitySAO::setPos(const v3f &pos)
  313. {
  314. if(isAttached())
  315. return;
  316. m_base_position = pos;
  317. sendPosition(false, true);
  318. }
  319. void LuaEntitySAO::moveTo(v3f pos, bool continuous)
  320. {
  321. if(isAttached())
  322. return;
  323. m_base_position = pos;
  324. if(!continuous)
  325. sendPosition(true, true);
  326. }
  327. float LuaEntitySAO::getMinimumSavedMovement()
  328. {
  329. return 0.1 * BS;
  330. }
  331. std::string LuaEntitySAO::getDescription()
  332. {
  333. std::ostringstream oss;
  334. oss << "LuaEntitySAO \"" << m_init_name << "\" ";
  335. auto pos = floatToInt(m_base_position, BS);
  336. oss << "at " << pos;
  337. return oss.str();
  338. }
  339. void LuaEntitySAO::setHP(s32 hp, const PlayerHPChangeReason &reason)
  340. {
  341. m_hp = rangelim(hp, 0, U16_MAX);
  342. sendPunchCommand();
  343. if (m_hp == 0 && !isGone()) {
  344. clearParentAttachment();
  345. clearChildAttachments();
  346. if (m_registered) {
  347. ServerActiveObject *killer = nullptr;
  348. if (reason.type == PlayerHPChangeReason::PLAYER_PUNCH)
  349. killer = reason.object;
  350. m_env->getScriptIface()->luaentity_on_death(m_id, killer);
  351. }
  352. markForRemoval();
  353. }
  354. }
  355. u16 LuaEntitySAO::getHP() const
  356. {
  357. return m_hp;
  358. }
  359. void LuaEntitySAO::setVelocity(v3f velocity)
  360. {
  361. m_velocity = velocity;
  362. }
  363. v3f LuaEntitySAO::getVelocity()
  364. {
  365. return m_velocity;
  366. }
  367. void LuaEntitySAO::setAcceleration(v3f acceleration)
  368. {
  369. m_acceleration = acceleration;
  370. }
  371. v3f LuaEntitySAO::getAcceleration()
  372. {
  373. return m_acceleration;
  374. }
  375. void LuaEntitySAO::setTextureMod(const std::string &mod)
  376. {
  377. m_current_texture_modifier = mod;
  378. // create message and add to list
  379. m_messages_out.emplace(getId(), true, generateSetTextureModCommand());
  380. }
  381. std::string LuaEntitySAO::getTextureMod() const
  382. {
  383. return m_current_texture_modifier;
  384. }
  385. std::string LuaEntitySAO::generateSetTextureModCommand() const
  386. {
  387. std::ostringstream os(std::ios::binary);
  388. // command
  389. writeU8(os, AO_CMD_SET_TEXTURE_MOD);
  390. // parameters
  391. os << serializeString16(m_current_texture_modifier);
  392. return os.str();
  393. }
  394. std::string LuaEntitySAO::generateSetSpriteCommand(v2s16 p, u16 num_frames,
  395. f32 framelength, bool select_horiz_by_yawpitch)
  396. {
  397. std::ostringstream os(std::ios::binary);
  398. // command
  399. writeU8(os, AO_CMD_SET_SPRITE);
  400. // parameters
  401. writeV2S16(os, p);
  402. writeU16(os, num_frames);
  403. writeF32(os, framelength);
  404. writeU8(os, select_horiz_by_yawpitch);
  405. return os.str();
  406. }
  407. void LuaEntitySAO::setSprite(v2s16 p, int num_frames, float framelength,
  408. bool select_horiz_by_yawpitch)
  409. {
  410. std::string str = generateSetSpriteCommand(
  411. p,
  412. num_frames,
  413. framelength,
  414. select_horiz_by_yawpitch
  415. );
  416. // create message and add to list
  417. m_messages_out.emplace(getId(), true, str);
  418. }
  419. std::string LuaEntitySAO::getName()
  420. {
  421. return m_init_name;
  422. }
  423. std::string LuaEntitySAO::getPropertyPacket()
  424. {
  425. return generateSetPropertiesCommand(m_prop);
  426. }
  427. void LuaEntitySAO::sendPosition(bool do_interpolate, bool is_movement_end)
  428. {
  429. // If the object is attached client-side, don't waste bandwidth sending its position to clients
  430. if(isAttached())
  431. return;
  432. // Send attachment updates instantly to the client prior updating position
  433. sendOutdatedData();
  434. m_last_sent_move_precision = m_base_position.getDistanceFrom(
  435. m_last_sent_position);
  436. m_last_sent_position_timer = 0;
  437. m_last_sent_position = m_base_position;
  438. m_last_sent_velocity = m_velocity;
  439. //m_last_sent_acceleration = m_acceleration;
  440. m_last_sent_rotation = m_rotation;
  441. float update_interval = m_env->getSendRecommendedInterval();
  442. std::string str = generateUpdatePositionCommand(
  443. m_base_position,
  444. m_velocity,
  445. m_acceleration,
  446. m_rotation,
  447. do_interpolate,
  448. is_movement_end,
  449. update_interval
  450. );
  451. // create message and add to list
  452. m_messages_out.emplace(getId(), false, str);
  453. }
  454. bool LuaEntitySAO::getCollisionBox(aabb3f *toset) const
  455. {
  456. if (m_prop.physical)
  457. {
  458. //update collision box
  459. toset->MinEdge = m_prop.collisionbox.MinEdge * BS;
  460. toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS;
  461. toset->MinEdge += m_base_position;
  462. toset->MaxEdge += m_base_position;
  463. return true;
  464. }
  465. return false;
  466. }
  467. bool LuaEntitySAO::getSelectionBox(aabb3f *toset) const
  468. {
  469. if (!m_prop.is_visible) {
  470. return false;
  471. }
  472. toset->MinEdge = m_prop.selectionbox.MinEdge * BS;
  473. toset->MaxEdge = m_prop.selectionbox.MaxEdge * BS;
  474. return true;
  475. }
  476. bool LuaEntitySAO::collideWithObjects() const
  477. {
  478. return m_prop.collideWithObjects;
  479. }