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