3 Copyright (C) 2010-2017 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 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.
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 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser 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 "util/serialize.h"
21 #include "util/pointedthing.h"
22 #include "clientenvironment.h"
23 #include "clientsimpleobject.h"
24 #include "clientmap.h"
25 #include "scripting_client.h"
26 #include "mapblock_mesh.h"
28 #include "collision.h"
31 #include "voxelalgorithms.h"
39 ClientEnvironment::ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr,
40 ITextureSource *texturesource, Client *client,
45 m_texturesource(texturesource),
50 memset(attachement_parent_ids, zero, sizeof(attachement_parent_ids));
53 ClientEnvironment::~ClientEnvironment()
55 // delete active objects
56 for (ClientActiveObjectMap::iterator i = m_active_objects.begin();
57 i != m_active_objects.end(); ++i) {
61 for(std::vector<ClientSimpleObject*>::iterator
62 i = m_simple_objects.begin(); i != m_simple_objects.end(); ++i) {
69 delete m_local_player;
72 Map & ClientEnvironment::getMap()
77 ClientMap & ClientEnvironment::getClientMap()
82 void ClientEnvironment::setLocalPlayer(LocalPlayer *player)
84 DSTACK(FUNCTION_NAME);
86 It is a failure if already is a local player
88 FATAL_ERROR_IF(m_local_player != NULL,
89 "Local player already allocated");
91 m_local_player = player;
94 void ClientEnvironment::step(float dtime)
96 DSTACK(FUNCTION_NAME);
98 /* Step time of day */
102 bool fly_allowed = m_client->checkLocalPrivilege("fly");
103 bool free_move = fly_allowed && g_settings->getBool("free_move");
106 LocalPlayer *lplayer = getLocalPlayer();
108 // collision info queue
109 std::vector<CollisionInfo> player_collisions;
112 Get the speed the player is going
114 bool is_climbing = lplayer->is_climbing;
116 f32 player_speed = lplayer->getSpeed().getLength();
119 Maximum position increment
121 //f32 position_max_increment = 0.05*BS;
122 f32 position_max_increment = 0.1*BS;
124 // Maximum time increment (for collision detection etc)
125 // time = distance / speed
126 f32 dtime_max_increment = 1;
127 if(player_speed > 0.001)
128 dtime_max_increment = position_max_increment / player_speed;
130 // Maximum time increment is 10ms or lower
131 if(dtime_max_increment > 0.01)
132 dtime_max_increment = 0.01;
134 // Don't allow overly huge dtime
138 f32 dtime_downcount = dtime;
141 Stuff that has a maximum time increment
150 if(dtime_downcount > dtime_max_increment)
152 dtime_part = dtime_max_increment;
153 dtime_downcount -= dtime_part;
157 dtime_part = dtime_downcount;
159 Setting this to 0 (no -=dtime_part) disables an infinite loop
160 when dtime_part is so small that dtime_downcount -= dtime_part
172 if(!free_move && !is_climbing)
175 v3f speed = lplayer->getSpeed();
176 if(!lplayer->in_liquid)
177 speed.Y -= lplayer->movement_gravity * lplayer->physics_override_gravity * dtime_part * 2;
179 // Liquid floating / sinking
180 if(lplayer->in_liquid && !lplayer->swimming_vertical)
181 speed.Y -= lplayer->movement_liquid_sink * dtime_part * 2;
184 if(lplayer->in_liquid_stable || lplayer->in_liquid)
186 // How much the node's viscosity blocks movement, ranges between 0 and 1
187 // Should match the scale at which viscosity increase affects other liquid attributes
188 const f32 viscosity_factor = 0.3;
190 v3f d_wanted = -speed / lplayer->movement_liquid_fluidity;
191 f32 dl = d_wanted.getLength();
192 if(dl > lplayer->movement_liquid_fluidity_smooth)
193 dl = lplayer->movement_liquid_fluidity_smooth;
194 dl *= (lplayer->liquid_viscosity * viscosity_factor) + (1 - viscosity_factor);
196 v3f d = d_wanted.normalize() * dl;
200 lplayer->setSpeed(speed);
205 This also does collision detection.
207 lplayer->move(dtime_part, this, position_max_increment,
211 while(dtime_downcount > 0.001);
213 //std::cout<<"Looped "<<loopcount<<" times."<<std::endl;
215 for(std::vector<CollisionInfo>::iterator i = player_collisions.begin();
216 i != player_collisions.end(); ++i) {
217 CollisionInfo &info = *i;
218 v3f speed_diff = info.new_speed - info.old_speed;;
219 // Handle only fall damage
220 // (because otherwise walking against something in fast_move kills you)
221 if(speed_diff.Y < 0 || info.old_speed.Y >= 0)
223 // Get rid of other components
226 f32 pre_factor = 1; // 1 hp per node/s
227 f32 tolerance = BS*14; // 5 without damage
228 f32 post_factor = 1; // 1 hp per node/s
229 if(info.type == COLLISION_NODE)
231 const ContentFeatures &f = m_client->ndef()->
232 get(m_map->getNodeNoEx(info.node_p));
233 // Determine fall damage multiplier
234 int addp = itemgroup_get(f.groups, "fall_damage_add_percent");
235 pre_factor = 1.0 + (float)addp/100.0;
237 float speed = pre_factor * speed_diff.getLength();
238 if (speed > tolerance) {
239 f32 damage_f = (speed - tolerance) / BS * post_factor;
240 u8 damage = (u8)MYMIN(damage_f + 0.5, 255);
242 damageLocalPlayer(damage, true);
243 MtEvent *e = new SimpleTriggerEvent("PlayerFallingDamage");
244 m_client->event()->put(e);
249 if (m_client->moddingEnabled()) {
250 m_script->environment_step(dtime);
253 // Protocol v29 make this behaviour obsolete
254 if (getGameDef()->getProtoVersion() < 29) {
255 if (m_lava_hurt_interval.step(dtime, 1.0)) {
256 v3f pf = lplayer->getPosition();
258 // Feet, middle and head
259 v3s16 p1 = floatToInt(pf + v3f(0, BS * 0.1, 0), BS);
260 MapNode n1 = m_map->getNodeNoEx(p1);
261 v3s16 p2 = floatToInt(pf + v3f(0, BS * 0.8, 0), BS);
262 MapNode n2 = m_map->getNodeNoEx(p2);
263 v3s16 p3 = floatToInt(pf + v3f(0, BS * 1.6, 0), BS);
264 MapNode n3 = m_map->getNodeNoEx(p3);
266 u32 damage_per_second = 0;
267 damage_per_second = MYMAX(damage_per_second,
268 m_client->ndef()->get(n1).damage_per_second);
269 damage_per_second = MYMAX(damage_per_second,
270 m_client->ndef()->get(n2).damage_per_second);
271 damage_per_second = MYMAX(damage_per_second,
272 m_client->ndef()->get(n3).damage_per_second);
274 if (damage_per_second != 0)
275 damageLocalPlayer(damage_per_second, true);
281 if (m_drowning_interval.step(dtime, 2.0)) {
282 v3f pf = lplayer->getPosition();
285 v3s16 p = floatToInt(pf + v3f(0, BS * 1.6, 0), BS);
286 MapNode n = m_map->getNodeNoEx(p);
287 ContentFeatures c = m_client->ndef()->get(n);
288 u8 drowning_damage = c.drowning;
289 if (drowning_damage > 0 && lplayer->hp > 0) {
290 u16 breath = lplayer->getBreath();
297 lplayer->setBreath(breath);
298 updateLocalPlayerBreath(breath);
301 if (lplayer->getBreath() == 0 && drowning_damage > 0) {
302 damageLocalPlayer(drowning_damage, true);
305 if (m_breathing_interval.step(dtime, 0.5)) {
306 v3f pf = lplayer->getPosition();
309 v3s16 p = floatToInt(pf + v3f(0, BS * 1.6, 0), BS);
310 MapNode n = m_map->getNodeNoEx(p);
311 ContentFeatures c = m_client->ndef()->get(n);
313 lplayer->setBreath(11);
314 } else if (c.drowning == 0) {
315 u16 breath = lplayer->getBreath();
318 lplayer->setBreath(breath);
319 updateLocalPlayerBreath(breath);
325 // Update lighting on local player (used for wield item)
326 u32 day_night_ratio = getDayNightRatio();
330 // On InvalidPositionException, use this as default
331 // (day: LIGHT_SUN, night: 0)
332 MapNode node_at_lplayer(CONTENT_AIR, 0x0f, 0);
334 v3s16 p = lplayer->getLightPosition();
335 node_at_lplayer = m_map->getNodeNoEx(p);
337 u16 light = getInteriorLight(node_at_lplayer, 0, m_client->ndef());
338 final_color_blend(&lplayer->light_color, light, day_night_ratio);
342 Step active objects and update lighting of them
345 g_profiler->avg("CEnv: num of objects", m_active_objects.size());
346 bool update_lighting = m_active_object_light_update_interval.step(dtime, 0.21);
347 for (ClientActiveObjectMap::iterator i = m_active_objects.begin();
348 i != m_active_objects.end(); ++i) {
349 ClientActiveObject* obj = i->second;
351 obj->step(dtime, this);
360 v3s16 p = obj->getLightPosition();
361 MapNode n = m_map->getNodeNoEx(p, &pos_ok);
363 light = n.getLightBlend(day_night_ratio, m_client->ndef());
365 light = blend_light(day_night_ratio, LIGHT_SUN, 0);
367 obj->updateLight(light);
372 Step and handle simple objects
374 g_profiler->avg("CEnv: num of simple objects", m_simple_objects.size());
375 for(std::vector<ClientSimpleObject*>::iterator
376 i = m_simple_objects.begin(); i != m_simple_objects.end();) {
377 std::vector<ClientSimpleObject*>::iterator cur = i;
378 ClientSimpleObject *simple = *cur;
381 if(simple->m_to_be_removed) {
383 i = m_simple_objects.erase(cur);
391 void ClientEnvironment::addSimpleObject(ClientSimpleObject *simple)
393 m_simple_objects.push_back(simple);
396 GenericCAO* ClientEnvironment::getGenericCAO(u16 id)
398 ClientActiveObject *obj = getActiveObject(id);
399 if (obj && obj->getType() == ACTIVEOBJECT_TYPE_GENERIC)
400 return (GenericCAO*) obj;
405 ClientActiveObject* ClientEnvironment::getActiveObject(u16 id)
407 ClientActiveObjectMap::iterator n = m_active_objects.find(id);
408 if (n == m_active_objects.end())
413 bool isFreeClientActiveObjectId(const u16 id,
414 ClientActiveObjectMap &objects)
419 return objects.find(id) == objects.end();
422 u16 getFreeClientActiveObjectId(ClientActiveObjectMap &objects)
424 //try to reuse id's as late as possible
425 static u16 last_used_id = 0;
426 u16 startid = last_used_id;
429 if (isFreeClientActiveObjectId(last_used_id, objects))
432 if (last_used_id == startid)
437 u16 ClientEnvironment::addActiveObject(ClientActiveObject *object)
439 assert(object); // Pre-condition
440 if(object->getId() == 0)
442 u16 new_id = getFreeClientActiveObjectId(m_active_objects);
445 infostream<<"ClientEnvironment::addActiveObject(): "
446 <<"no free ids available"<<std::endl;
450 object->setId(new_id);
452 if (!isFreeClientActiveObjectId(object->getId(), m_active_objects)) {
453 infostream<<"ClientEnvironment::addActiveObject(): "
454 <<"id is not free ("<<object->getId()<<")"<<std::endl;
458 infostream<<"ClientEnvironment::addActiveObject(): "
459 <<"added (id="<<object->getId()<<")"<<std::endl;
460 m_active_objects[object->getId()] = object;
461 object->addToScene(m_smgr, m_texturesource, m_irr);
462 { // Update lighting immediately
467 v3s16 p = object->getLightPosition();
468 MapNode n = m_map->getNodeNoEx(p, &pos_ok);
470 light = n.getLightBlend(getDayNightRatio(), m_client->ndef());
472 light = blend_light(getDayNightRatio(), LIGHT_SUN, 0);
474 object->updateLight(light);
476 return object->getId();
479 void ClientEnvironment::addActiveObject(u16 id, u8 type,
480 const std::string &init_data)
482 ClientActiveObject* obj =
483 ClientActiveObject::create((ActiveObjectType) type, m_client, this);
486 infostream<<"ClientEnvironment::addActiveObject(): "
487 <<"id="<<id<<" type="<<type<<": Couldn't create object"
496 obj->initialize(init_data);
498 catch(SerializationError &e)
500 errorstream<<"ClientEnvironment::addActiveObject():"
501 <<" id="<<id<<" type="<<type
502 <<": SerializationError in initialize(): "
504 <<": init_data="<<serializeJsonString(init_data)
508 addActiveObject(obj);
511 void ClientEnvironment::removeActiveObject(u16 id)
513 verbosestream<<"ClientEnvironment::removeActiveObject(): "
514 <<"id="<<id<<std::endl;
515 ClientActiveObject* obj = getActiveObject(id);
517 infostream<<"ClientEnvironment::removeActiveObject(): "
518 <<"id="<<id<<" not found"<<std::endl;
521 obj->removeFromScene(true);
523 m_active_objects.erase(id);
526 void ClientEnvironment::processActiveObjectMessage(u16 id, const std::string &data)
528 ClientActiveObject *obj = getActiveObject(id);
530 infostream << "ClientEnvironment::processActiveObjectMessage():"
531 << " got message for id=" << id << ", which doesn't exist."
537 obj->processMessage(data);
538 } catch (SerializationError &e) {
539 errorstream<<"ClientEnvironment::processActiveObjectMessage():"
540 << " id=" << id << " type=" << obj->getType()
541 << " SerializationError in processMessage(): " << e.what()
547 Callbacks for activeobjects
550 void ClientEnvironment::damageLocalPlayer(u8 damage, bool handle_hp)
552 LocalPlayer *lplayer = getLocalPlayer();
556 if (lplayer->hp > damage)
557 lplayer->hp -= damage;
562 ClientEnvEvent event;
563 event.type = CEE_PLAYER_DAMAGE;
564 event.player_damage.amount = damage;
565 event.player_damage.send_to_server = handle_hp;
566 m_client_event_queue.push(event);
569 void ClientEnvironment::updateLocalPlayerBreath(u16 breath)
571 ClientEnvEvent event;
572 event.type = CEE_PLAYER_BREATH;
573 event.player_breath.amount = breath;
574 m_client_event_queue.push(event);
578 Client likes to call these
581 void ClientEnvironment::getActiveObjects(v3f origin, f32 max_d,
582 std::vector<DistanceSortedActiveObject> &dest)
584 for (ClientActiveObjectMap::iterator i = m_active_objects.begin();
585 i != m_active_objects.end(); ++i) {
586 ClientActiveObject* obj = i->second;
588 f32 d = (obj->getPosition() - origin).getLength();
593 DistanceSortedActiveObject dso(obj, d);
599 ClientEnvEvent ClientEnvironment::getClientEnvEvent()
601 FATAL_ERROR_IF(m_client_event_queue.empty(),
602 "ClientEnvironment::getClientEnvEvent(): queue is empty");
604 ClientEnvEvent event = m_client_event_queue.front();
605 m_client_event_queue.pop();
609 ClientActiveObject * ClientEnvironment::getSelectedActiveObject(
610 const core::line3d<f32> &shootline_on_map, v3f *intersection_point,
611 v3s16 *intersection_normal)
613 std::vector<DistanceSortedActiveObject> objects;
614 getActiveObjects(shootline_on_map.start,
615 shootline_on_map.getLength() + 3, objects);
616 const v3f line_vector = shootline_on_map.getVector();
619 // After this, the closest object is the first in the array.
620 std::sort(objects.begin(), objects.end());
622 /* Because objects can have different nodebox sizes,
623 * the object whose center is the nearest isn't necessarily
624 * the closest one. If an object is found, don't stop
627 f32 d_min = shootline_on_map.getLength();
628 ClientActiveObject *nearest_obj = NULL;
629 for (u32 i = 0; i < objects.size(); i++) {
630 ClientActiveObject *obj = objects[i].obj;
632 aabb3f *selection_box = obj->getSelectionBox();
633 if (selection_box == NULL)
636 v3f pos = obj->getPosition();
638 aabb3f offsetted_box(selection_box->MinEdge + pos,
639 selection_box->MaxEdge + pos);
641 if (offsetted_box.getCenter().getDistanceFrom(
642 shootline_on_map.start) > d_min + 9.6f*BS) {
643 // Probably there is no active object that has bigger nodebox than
644 // (-5.5,-5.5,-5.5,5.5,5.5,5.5)
649 v3f current_intersection;
650 v3s16 current_normal;
651 if (boxLineCollision(offsetted_box, shootline_on_map.start, line_vector,
652 ¤t_intersection, ¤t_normal)) {
653 f32 d_current = current_intersection.getDistanceFrom(
654 shootline_on_map.start);
655 if (d_current <= d_min) {
658 *intersection_point = current_intersection;
659 *intersection_normal = current_normal;
668 Check if a node is pointable
670 static inline bool isPointableNode(const MapNode &n,
671 INodeDefManager *ndef, bool liquids_pointable)
673 const ContentFeatures &features = ndef->get(n);
674 return features.pointable ||
675 (liquids_pointable && features.isLiquid());
678 PointedThing ClientEnvironment::getPointedThing(
679 core::line3d<f32> shootline,
680 bool liquids_pointable,
681 bool look_for_object)
685 INodeDefManager *nodedef = m_map->getNodeDefManager();
687 core::aabbox3d<s16> maximal_exceed = nodedef->getSelectionBoxIntUnion();
688 // The code needs to search these nodes
689 core::aabbox3d<s16> search_range(-maximal_exceed.MaxEdge,
690 -maximal_exceed.MinEdge);
691 // If a node is found, there might be a larger node behind.
692 // To find it, we have to go further.
693 s16 maximal_overcheck =
694 std::max(abs(search_range.MinEdge.X), abs(search_range.MaxEdge.X))
695 + std::max(abs(search_range.MinEdge.Y), abs(search_range.MaxEdge.Y))
696 + std::max(abs(search_range.MinEdge.Z), abs(search_range.MaxEdge.Z));
698 const v3f original_vector = shootline.getVector();
699 const f32 original_length = original_vector.getLength();
701 f32 min_distance = original_length;
703 // First try to find an active object
704 if (look_for_object) {
705 ClientActiveObject *selected_object = getSelectedActiveObject(
706 shootline, &result.intersection_point,
707 &result.intersection_normal);
709 if (selected_object != NULL) {
711 (result.intersection_point - shootline.start).getLength();
713 result.type = POINTEDTHING_OBJECT;
714 result.object_id = selected_object->getId();
719 if (original_length > 0) {
720 shootline.end = shootline.start
721 + shootline.getVector() / original_length * min_distance;
724 // Try to find a node that is closer than the selected active
725 // object (if it exists).
727 voxalgo::VoxelLineIterator iterator(shootline.start / BS,
728 shootline.getVector() / BS);
729 v3s16 oldnode = iterator.m_current_node_pos;
730 // Indicates that a node was found.
731 bool is_node_found = false;
732 // If a node is found, it is possible that there's a node
733 // behind it with a large nodebox, so continue the search.
734 u16 node_foundcounter = 0;
735 // If a node is found, this is the center of the
736 // first nodebox the shootline meets.
737 v3f found_boxcenter(0, 0, 0);
738 // The untested nodes are in this range.
739 core::aabbox3d<s16> new_nodes;
741 // Test the nodes around the current node in search_range.
742 new_nodes = search_range;
743 new_nodes.MinEdge += iterator.m_current_node_pos;
744 new_nodes.MaxEdge += iterator.m_current_node_pos;
746 // Only check new nodes
747 v3s16 delta = iterator.m_current_node_pos - oldnode;
749 new_nodes.MinEdge.X = new_nodes.MaxEdge.X;
750 else if (delta.X < 0)
751 new_nodes.MaxEdge.X = new_nodes.MinEdge.X;
752 else if (delta.Y > 0)
753 new_nodes.MinEdge.Y = new_nodes.MaxEdge.Y;
754 else if (delta.Y < 0)
755 new_nodes.MaxEdge.Y = new_nodes.MinEdge.Y;
756 else if (delta.Z > 0)
757 new_nodes.MinEdge.Z = new_nodes.MaxEdge.Z;
758 else if (delta.Z < 0)
759 new_nodes.MaxEdge.Z = new_nodes.MinEdge.Z;
761 // For each untested node
762 for (s16 x = new_nodes.MinEdge.X; x <= new_nodes.MaxEdge.X; x++) {
763 for (s16 y = new_nodes.MinEdge.Y; y <= new_nodes.MaxEdge.Y; y++) {
764 for (s16 z = new_nodes.MinEdge.Z; z <= new_nodes.MaxEdge.Z; z++) {
767 bool is_valid_position;
769 n = m_map->getNodeNoEx(np, &is_valid_position);
770 if (!(is_valid_position &&
771 isPointableNode(n, nodedef, liquids_pointable))) {
774 std::vector<aabb3f> boxes;
775 n.getSelectionBoxes(nodedef, &boxes,
776 n.getNeighbors(np, m_map));
778 v3f npf = intToFloat(np, BS);
779 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
780 i != boxes.end(); ++i) {
784 v3f intersection_point;
785 v3s16 intersection_normal;
786 if (!boxLineCollision(box, shootline.start, shootline.getVector(),
787 &intersection_point, &intersection_normal)) {
790 f32 distance = (intersection_point - shootline.start).getLength();
791 if (distance >= min_distance) {
794 result.type = POINTEDTHING_NODE;
795 result.node_undersurface = np;
796 result.intersection_point = intersection_point;
797 result.intersection_normal = intersection_normal;
798 found_boxcenter = box.getCenter();
799 min_distance = distance;
800 is_node_found = true;
807 if (node_foundcounter > maximal_overcheck) {
812 if (iterator.hasNext()) {
813 oldnode = iterator.m_current_node_pos;
821 // Set undersurface and abovesurface nodes
823 v3f fake_intersection = result.intersection_point;
824 // Move intersection towards its source block.
825 if (fake_intersection.X < found_boxcenter.X)
826 fake_intersection.X += d;
828 fake_intersection.X -= d;
830 if (fake_intersection.Y < found_boxcenter.Y)
831 fake_intersection.Y += d;
833 fake_intersection.Y -= d;
835 if (fake_intersection.Z < found_boxcenter.Z)
836 fake_intersection.Z += d;
838 fake_intersection.Z -= d;
840 result.node_real_undersurface = floatToInt(fake_intersection, BS);
841 result.node_abovesurface = result.node_real_undersurface
842 + result.intersection_normal;