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"
34 #include "client/renderingengine.h"
40 ClientEnvironment::ClientEnvironment(ClientMap *map,
41 ITextureSource *texturesource, Client *client):
44 m_texturesource(texturesource),
48 memset(attachement_parent_ids, zero, sizeof(attachement_parent_ids));
51 ClientEnvironment::~ClientEnvironment()
53 // delete active objects
54 for (ClientActiveObjectMap::iterator i = m_active_objects.begin();
55 i != m_active_objects.end(); ++i) {
59 for(std::vector<ClientSimpleObject*>::iterator
60 i = m_simple_objects.begin(); i != m_simple_objects.end(); ++i) {
67 delete m_local_player;
70 Map & ClientEnvironment::getMap()
75 ClientMap & ClientEnvironment::getClientMap()
80 void ClientEnvironment::setLocalPlayer(LocalPlayer *player)
82 DSTACK(FUNCTION_NAME);
84 It is a failure if already is a local player
86 FATAL_ERROR_IF(m_local_player != NULL,
87 "Local player already allocated");
89 m_local_player = player;
92 void ClientEnvironment::step(float dtime)
94 DSTACK(FUNCTION_NAME);
96 /* Step time of day */
100 bool fly_allowed = m_client->checkLocalPrivilege("fly");
101 bool free_move = fly_allowed && g_settings->getBool("free_move");
104 LocalPlayer *lplayer = getLocalPlayer();
106 // collision info queue
107 std::vector<CollisionInfo> player_collisions;
110 Get the speed the player is going
112 bool is_climbing = lplayer->is_climbing;
114 f32 player_speed = lplayer->getSpeed().getLength();
117 Maximum position increment
119 //f32 position_max_increment = 0.05*BS;
120 f32 position_max_increment = 0.1*BS;
122 // Maximum time increment (for collision detection etc)
123 // time = distance / speed
124 f32 dtime_max_increment = 1;
125 if(player_speed > 0.001)
126 dtime_max_increment = position_max_increment / player_speed;
128 // Maximum time increment is 10ms or lower
129 if(dtime_max_increment > 0.01)
130 dtime_max_increment = 0.01;
132 // Don't allow overly huge dtime
136 f32 dtime_downcount = dtime;
139 Stuff that has a maximum time increment
148 if(dtime_downcount > dtime_max_increment)
150 dtime_part = dtime_max_increment;
151 dtime_downcount -= dtime_part;
155 dtime_part = dtime_downcount;
157 Setting this to 0 (no -=dtime_part) disables an infinite loop
158 when dtime_part is so small that dtime_downcount -= dtime_part
170 if(!free_move && !is_climbing)
173 v3f speed = lplayer->getSpeed();
174 if(!lplayer->in_liquid)
175 speed.Y -= lplayer->movement_gravity * lplayer->physics_override_gravity * dtime_part * 2;
177 // Liquid floating / sinking
178 if(lplayer->in_liquid && !lplayer->swimming_vertical)
179 speed.Y -= lplayer->movement_liquid_sink * dtime_part * 2;
182 if(lplayer->in_liquid_stable || lplayer->in_liquid)
184 // How much the node's viscosity blocks movement, ranges between 0 and 1
185 // Should match the scale at which viscosity increase affects other liquid attributes
186 const f32 viscosity_factor = 0.3;
188 v3f d_wanted = -speed / lplayer->movement_liquid_fluidity;
189 f32 dl = d_wanted.getLength();
190 if(dl > lplayer->movement_liquid_fluidity_smooth)
191 dl = lplayer->movement_liquid_fluidity_smooth;
192 dl *= (lplayer->liquid_viscosity * viscosity_factor) + (1 - viscosity_factor);
194 v3f d = d_wanted.normalize() * dl;
198 lplayer->setSpeed(speed);
203 This also does collision detection.
205 lplayer->move(dtime_part, this, position_max_increment,
209 while(dtime_downcount > 0.001);
211 //std::cout<<"Looped "<<loopcount<<" times."<<std::endl;
213 for(std::vector<CollisionInfo>::iterator i = player_collisions.begin();
214 i != player_collisions.end(); ++i) {
215 CollisionInfo &info = *i;
216 v3f speed_diff = info.new_speed - info.old_speed;;
217 // Handle only fall damage
218 // (because otherwise walking against something in fast_move kills you)
219 if(speed_diff.Y < 0 || info.old_speed.Y >= 0)
221 // Get rid of other components
224 f32 pre_factor = 1; // 1 hp per node/s
225 f32 tolerance = BS*14; // 5 without damage
226 f32 post_factor = 1; // 1 hp per node/s
227 if(info.type == COLLISION_NODE)
229 const ContentFeatures &f = m_client->ndef()->
230 get(m_map->getNodeNoEx(info.node_p));
231 // Determine fall damage multiplier
232 int addp = itemgroup_get(f.groups, "fall_damage_add_percent");
233 pre_factor = 1.0 + (float)addp/100.0;
235 float speed = pre_factor * speed_diff.getLength();
236 if (speed > tolerance) {
237 f32 damage_f = (speed - tolerance) / BS * post_factor;
238 u8 damage = (u8)MYMIN(damage_f + 0.5, 255);
240 damageLocalPlayer(damage, true);
241 MtEvent *e = new SimpleTriggerEvent("PlayerFallingDamage");
242 m_client->event()->put(e);
247 if (m_client->moddingEnabled()) {
248 m_script->environment_step(dtime);
251 // Protocol v29 make this behaviour obsolete
252 if (getGameDef()->getProtoVersion() < 29) {
253 if (m_lava_hurt_interval.step(dtime, 1.0)) {
254 v3f pf = lplayer->getPosition();
256 // Feet, middle and head
257 v3s16 p1 = floatToInt(pf + v3f(0, BS * 0.1, 0), BS);
258 MapNode n1 = m_map->getNodeNoEx(p1);
259 v3s16 p2 = floatToInt(pf + v3f(0, BS * 0.8, 0), BS);
260 MapNode n2 = m_map->getNodeNoEx(p2);
261 v3s16 p3 = floatToInt(pf + v3f(0, BS * 1.6, 0), BS);
262 MapNode n3 = m_map->getNodeNoEx(p3);
264 u32 damage_per_second = 0;
265 damage_per_second = MYMAX(damage_per_second,
266 m_client->ndef()->get(n1).damage_per_second);
267 damage_per_second = MYMAX(damage_per_second,
268 m_client->ndef()->get(n2).damage_per_second);
269 damage_per_second = MYMAX(damage_per_second,
270 m_client->ndef()->get(n3).damage_per_second);
272 if (damage_per_second != 0)
273 damageLocalPlayer(damage_per_second, true);
279 if (m_drowning_interval.step(dtime, 2.0)) {
280 v3f pf = lplayer->getPosition();
283 v3s16 p = floatToInt(pf + v3f(0, BS * 1.6, 0), BS);
284 MapNode n = m_map->getNodeNoEx(p);
285 ContentFeatures c = m_client->ndef()->get(n);
286 u8 drowning_damage = c.drowning;
287 if (drowning_damage > 0 && lplayer->hp > 0) {
288 u16 breath = lplayer->getBreath();
295 lplayer->setBreath(breath);
296 updateLocalPlayerBreath(breath);
299 if (lplayer->getBreath() == 0 && drowning_damage > 0) {
300 damageLocalPlayer(drowning_damage, true);
303 if (m_breathing_interval.step(dtime, 0.5)) {
304 v3f pf = lplayer->getPosition();
307 v3s16 p = floatToInt(pf + v3f(0, BS * 1.6, 0), BS);
308 MapNode n = m_map->getNodeNoEx(p);
309 ContentFeatures c = m_client->ndef()->get(n);
311 lplayer->setBreath(11);
312 } else if (c.drowning == 0) {
313 u16 breath = lplayer->getBreath();
316 lplayer->setBreath(breath);
317 updateLocalPlayerBreath(breath);
323 // Update lighting on local player (used for wield item)
324 u32 day_night_ratio = getDayNightRatio();
328 // On InvalidPositionException, use this as default
329 // (day: LIGHT_SUN, night: 0)
330 MapNode node_at_lplayer(CONTENT_AIR, 0x0f, 0);
332 v3s16 p = lplayer->getLightPosition();
333 node_at_lplayer = m_map->getNodeNoEx(p);
335 u16 light = getInteriorLight(node_at_lplayer, 0, m_client->ndef());
336 final_color_blend(&lplayer->light_color, light, day_night_ratio);
340 Step active objects and update lighting of them
343 g_profiler->avg("CEnv: num of objects", m_active_objects.size());
344 bool update_lighting = m_active_object_light_update_interval.step(dtime, 0.21);
345 for (ClientActiveObjectMap::iterator i = m_active_objects.begin();
346 i != m_active_objects.end(); ++i) {
347 ClientActiveObject* obj = i->second;
349 obj->step(dtime, this);
358 v3s16 p = obj->getLightPosition();
359 MapNode n = m_map->getNodeNoEx(p, &pos_ok);
361 light = n.getLightBlend(day_night_ratio, m_client->ndef());
363 light = blend_light(day_night_ratio, LIGHT_SUN, 0);
365 obj->updateLight(light);
370 Step and handle simple objects
372 g_profiler->avg("CEnv: num of simple objects", m_simple_objects.size());
373 for(std::vector<ClientSimpleObject*>::iterator
374 i = m_simple_objects.begin(); i != m_simple_objects.end();) {
375 std::vector<ClientSimpleObject*>::iterator cur = i;
376 ClientSimpleObject *simple = *cur;
379 if(simple->m_to_be_removed) {
381 i = m_simple_objects.erase(cur);
389 void ClientEnvironment::addSimpleObject(ClientSimpleObject *simple)
391 m_simple_objects.push_back(simple);
394 GenericCAO* ClientEnvironment::getGenericCAO(u16 id)
396 ClientActiveObject *obj = getActiveObject(id);
397 if (obj && obj->getType() == ACTIVEOBJECT_TYPE_GENERIC)
398 return (GenericCAO*) obj;
403 ClientActiveObject* ClientEnvironment::getActiveObject(u16 id)
405 ClientActiveObjectMap::iterator n = m_active_objects.find(id);
406 if (n == m_active_objects.end())
411 bool isFreeClientActiveObjectId(const u16 id,
412 ClientActiveObjectMap &objects)
417 return objects.find(id) == objects.end();
420 u16 getFreeClientActiveObjectId(ClientActiveObjectMap &objects)
422 //try to reuse id's as late as possible
423 static u16 last_used_id = 0;
424 u16 startid = last_used_id;
427 if (isFreeClientActiveObjectId(last_used_id, objects))
430 if (last_used_id == startid)
435 u16 ClientEnvironment::addActiveObject(ClientActiveObject *object)
437 assert(object); // Pre-condition
438 if(object->getId() == 0)
440 u16 new_id = getFreeClientActiveObjectId(m_active_objects);
443 infostream<<"ClientEnvironment::addActiveObject(): "
444 <<"no free ids available"<<std::endl;
448 object->setId(new_id);
450 if (!isFreeClientActiveObjectId(object->getId(), m_active_objects)) {
451 infostream<<"ClientEnvironment::addActiveObject(): "
452 <<"id is not free ("<<object->getId()<<")"<<std::endl;
456 infostream<<"ClientEnvironment::addActiveObject(): "
457 <<"added (id="<<object->getId()<<")"<<std::endl;
458 m_active_objects[object->getId()] = object;
459 object->addToScene(m_texturesource);
460 { // Update lighting immediately
465 v3s16 p = object->getLightPosition();
466 MapNode n = m_map->getNodeNoEx(p, &pos_ok);
468 light = n.getLightBlend(getDayNightRatio(), m_client->ndef());
470 light = blend_light(getDayNightRatio(), LIGHT_SUN, 0);
472 object->updateLight(light);
474 return object->getId();
477 void ClientEnvironment::addActiveObject(u16 id, u8 type,
478 const std::string &init_data)
480 ClientActiveObject* obj =
481 ClientActiveObject::create((ActiveObjectType) type, m_client, this);
484 infostream<<"ClientEnvironment::addActiveObject(): "
485 <<"id="<<id<<" type="<<type<<": Couldn't create object"
494 obj->initialize(init_data);
496 catch(SerializationError &e)
498 errorstream<<"ClientEnvironment::addActiveObject():"
499 <<" id="<<id<<" type="<<type
500 <<": SerializationError in initialize(): "
502 <<": init_data="<<serializeJsonString(init_data)
506 addActiveObject(obj);
509 void ClientEnvironment::removeActiveObject(u16 id)
511 verbosestream<<"ClientEnvironment::removeActiveObject(): "
512 <<"id="<<id<<std::endl;
513 ClientActiveObject* obj = getActiveObject(id);
515 infostream<<"ClientEnvironment::removeActiveObject(): "
516 <<"id="<<id<<" not found"<<std::endl;
519 obj->removeFromScene(true);
521 m_active_objects.erase(id);
524 void ClientEnvironment::processActiveObjectMessage(u16 id, const std::string &data)
526 ClientActiveObject *obj = getActiveObject(id);
528 infostream << "ClientEnvironment::processActiveObjectMessage():"
529 << " got message for id=" << id << ", which doesn't exist."
535 obj->processMessage(data);
536 } catch (SerializationError &e) {
537 errorstream<<"ClientEnvironment::processActiveObjectMessage():"
538 << " id=" << id << " type=" << obj->getType()
539 << " SerializationError in processMessage(): " << e.what()
545 Callbacks for activeobjects
548 void ClientEnvironment::damageLocalPlayer(u8 damage, bool handle_hp)
550 LocalPlayer *lplayer = getLocalPlayer();
554 if (lplayer->hp > damage)
555 lplayer->hp -= damage;
560 ClientEnvEvent event;
561 event.type = CEE_PLAYER_DAMAGE;
562 event.player_damage.amount = damage;
563 event.player_damage.send_to_server = handle_hp;
564 m_client_event_queue.push(event);
567 void ClientEnvironment::updateLocalPlayerBreath(u16 breath)
569 ClientEnvEvent event;
570 event.type = CEE_PLAYER_BREATH;
571 event.player_breath.amount = breath;
572 m_client_event_queue.push(event);
576 Client likes to call these
579 void ClientEnvironment::getActiveObjects(v3f origin, f32 max_d,
580 std::vector<DistanceSortedActiveObject> &dest)
582 for (ClientActiveObjectMap::iterator i = m_active_objects.begin();
583 i != m_active_objects.end(); ++i) {
584 ClientActiveObject* obj = i->second;
586 f32 d = (obj->getPosition() - origin).getLength();
591 DistanceSortedActiveObject dso(obj, d);
597 ClientEnvEvent ClientEnvironment::getClientEnvEvent()
599 FATAL_ERROR_IF(m_client_event_queue.empty(),
600 "ClientEnvironment::getClientEnvEvent(): queue is empty");
602 ClientEnvEvent event = m_client_event_queue.front();
603 m_client_event_queue.pop();
607 void ClientEnvironment::getSelectedActiveObjects(
608 const core::line3d<f32> &shootline_on_map,
609 std::vector<PointedThing> &objects)
611 std::vector<DistanceSortedActiveObject> allObjects;
612 getActiveObjects(shootline_on_map.start,
613 shootline_on_map.getLength() + 10.0f, allObjects);
614 const v3f line_vector = shootline_on_map.getVector();
616 for (u32 i = 0; i < allObjects.size(); i++) {
617 ClientActiveObject *obj = allObjects[i].obj;
618 aabb3f selection_box;
619 if (!obj->getSelectionBox(&selection_box))
621 v3f pos = obj->getPosition();
622 aabb3f offsetted_box(selection_box.MinEdge + pos,
623 selection_box.MaxEdge + pos);
625 v3f current_intersection;
626 v3s16 current_normal;
627 if (boxLineCollision(offsetted_box, shootline_on_map.start, line_vector,
628 ¤t_intersection, ¤t_normal)) {
629 objects.push_back(PointedThing(
630 (s16) obj->getId(), current_intersection, current_normal,
631 (current_intersection - shootline_on_map.start).getLengthSQ()));