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"
23 #include "clientenvironment.h"
24 #include "clientsimpleobject.h"
25 #include "clientmap.h"
26 #include "scripting_client.h"
27 #include "mapblock_mesh.h"
29 #include "collision.h"
33 #include "voxelalgorithms.h"
35 #include "content_cao.h"
37 #include "client/renderingengine.h"
43 ClientEnvironment::ClientEnvironment(ClientMap *map,
44 ITextureSource *texturesource, Client *client):
47 m_texturesource(texturesource),
52 ClientEnvironment::~ClientEnvironment()
56 for (auto &simple_object : m_simple_objects) {
63 delete m_local_player;
66 Map & ClientEnvironment::getMap()
71 ClientMap & ClientEnvironment::getClientMap()
76 void ClientEnvironment::setLocalPlayer(LocalPlayer *player)
79 It is a failure if already is a local player
81 FATAL_ERROR_IF(m_local_player != NULL,
82 "Local player already allocated");
84 m_local_player = player;
87 void ClientEnvironment::step(float dtime)
89 /* Step time of day */
93 bool fly_allowed = m_client->checkLocalPrivilege("fly");
94 bool free_move = fly_allowed && g_settings->getBool("free_move");
97 LocalPlayer *lplayer = getLocalPlayer();
99 // collision info queue
100 std::vector<CollisionInfo> player_collisions;
103 Get the speed the player is going
105 bool is_climbing = lplayer->is_climbing;
107 f32 player_speed = lplayer->getSpeed().getLength();
110 Maximum position increment
112 //f32 position_max_increment = 0.05*BS;
113 f32 position_max_increment = 0.1*BS;
115 // Maximum time increment (for collision detection etc)
116 // time = distance / speed
117 f32 dtime_max_increment = 1;
118 if(player_speed > 0.001)
119 dtime_max_increment = position_max_increment / player_speed;
121 // Maximum time increment is 10ms or lower
122 if(dtime_max_increment > 0.01)
123 dtime_max_increment = 0.01;
125 // Don't allow overly huge dtime
129 f32 dtime_downcount = dtime;
132 Stuff that has a maximum time increment
141 if(dtime_downcount > dtime_max_increment)
143 dtime_part = dtime_max_increment;
144 dtime_downcount -= dtime_part;
148 dtime_part = dtime_downcount;
150 Setting this to 0 (no -=dtime_part) disables an infinite loop
151 when dtime_part is so small that dtime_downcount -= dtime_part
163 if (!free_move && !is_climbing) {
165 v3f speed = lplayer->getSpeed();
166 if (!lplayer->in_liquid)
167 speed.Y -= lplayer->movement_gravity *
168 lplayer->physics_override_gravity * dtime_part * 2.0f;
170 // Liquid floating / sinking
171 if (lplayer->in_liquid && !lplayer->swimming_vertical &&
172 !lplayer->swimming_pitch)
173 speed.Y -= lplayer->movement_liquid_sink * dtime_part * 2.0f;
176 if (lplayer->in_liquid_stable || lplayer->in_liquid) {
177 // How much the node's viscosity blocks movement, ranges
178 // between 0 and 1. Should match the scale at which viscosity
179 // increase affects other liquid attributes.
180 static const f32 viscosity_factor = 0.3f;
182 v3f d_wanted = -speed / lplayer->movement_liquid_fluidity;
183 f32 dl = d_wanted.getLength();
184 if (dl > lplayer->movement_liquid_fluidity_smooth)
185 dl = lplayer->movement_liquid_fluidity_smooth;
187 dl *= (lplayer->liquid_viscosity * viscosity_factor) +
188 (1 - viscosity_factor);
189 v3f d = d_wanted.normalize() * (dl * dtime_part * 100.0f);
193 lplayer->setSpeed(speed);
198 This also does collision detection.
200 lplayer->move(dtime_part, this, position_max_increment,
203 } while (dtime_downcount > 0.001);
205 bool player_immortal = lplayer->getCAO() && lplayer->getCAO()->isImmortal();
207 for (const CollisionInfo &info : player_collisions) {
208 v3f speed_diff = info.new_speed - info.old_speed;;
209 // Handle only fall damage
210 // (because otherwise walking against something in fast_move kills you)
211 if (speed_diff.Y < 0 || info.old_speed.Y >= 0)
213 // Get rid of other components
216 f32 pre_factor = 1; // 1 hp per node/s
217 f32 tolerance = BS*14; // 5 without damage
218 f32 post_factor = 1; // 1 hp per node/s
219 if (info.type == COLLISION_NODE) {
220 const ContentFeatures &f = m_client->ndef()->
221 get(m_map->getNode(info.node_p));
222 // Determine fall damage multiplier
223 int addp = itemgroup_get(f.groups, "fall_damage_add_percent");
224 pre_factor = 1.0f + (float)addp / 100.0f;
226 float speed = pre_factor * speed_diff.getLength();
227 if (speed > tolerance && !player_immortal) {
228 f32 damage_f = (speed - tolerance) / BS * post_factor;
229 u16 damage = (u16)MYMIN(damage_f + 0.5, U16_MAX);
231 damageLocalPlayer(damage, true);
232 m_client->getEventManager()->put(
233 new SimpleTriggerEvent(MtEvent::PLAYER_FALLING_DAMAGE));
238 if (m_client->modsLoaded())
239 m_script->environment_step(dtime);
241 // Update lighting on local player (used for wield item)
242 u32 day_night_ratio = getDayNightRatio();
246 // On InvalidPositionException, use this as default
247 // (day: LIGHT_SUN, night: 0)
248 MapNode node_at_lplayer(CONTENT_AIR, 0x0f, 0);
250 v3s16 p = lplayer->getLightPosition();
251 node_at_lplayer = m_map->getNode(p);
253 u16 light = getInteriorLight(node_at_lplayer, 0, m_client->ndef());
254 final_color_blend(&lplayer->light_color, light, day_night_ratio);
258 Step active objects and update lighting of them
261 bool update_lighting = m_active_object_light_update_interval.step(dtime, 0.21);
262 auto cb_state = [this, dtime, update_lighting, day_night_ratio] (ClientActiveObject *cao) {
264 cao->step(dtime, this);
266 if (update_lighting) {
272 v3s16 p = cao->getLightPosition();
273 MapNode n = this->m_map->getNode(p, &pos_ok);
275 light = n.getLightBlend(day_night_ratio, m_client->ndef());
277 light = blend_light(day_night_ratio, LIGHT_SUN, 0);
279 cao->updateLight(light);
283 m_ao_manager.step(dtime, cb_state);
286 Step and handle simple objects
288 g_profiler->avg("ClientEnv: CSO count [#]", m_simple_objects.size());
289 for (auto i = m_simple_objects.begin(); i != m_simple_objects.end();) {
290 ClientSimpleObject *simple = *i;
293 if(simple->m_to_be_removed) {
295 i = m_simple_objects.erase(i);
303 void ClientEnvironment::addSimpleObject(ClientSimpleObject *simple)
305 m_simple_objects.push_back(simple);
308 GenericCAO* ClientEnvironment::getGenericCAO(u16 id)
310 ClientActiveObject *obj = getActiveObject(id);
311 if (obj && obj->getType() == ACTIVEOBJECT_TYPE_GENERIC)
312 return (GenericCAO*) obj;
317 bool isFreeClientActiveObjectId(const u16 id,
318 ClientActiveObjectMap &objects)
320 return id != 0 && objects.find(id) == objects.end();
324 u16 getFreeClientActiveObjectId(ClientActiveObjectMap &objects)
326 // try to reuse id's as late as possible
327 static u16 last_used_id = 0;
328 u16 startid = last_used_id;
331 if (isFreeClientActiveObjectId(last_used_id, objects))
334 if (last_used_id == startid)
339 u16 ClientEnvironment::addActiveObject(ClientActiveObject *object)
341 // Register object. If failed return zero id
342 if (!m_ao_manager.registerObject(object))
345 object->addToScene(m_texturesource);
347 // Update lighting immediately
352 v3s16 p = object->getLightPosition();
353 MapNode n = m_map->getNode(p, &pos_ok);
355 light = n.getLightBlend(getDayNightRatio(), m_client->ndef());
357 light = blend_light(getDayNightRatio(), LIGHT_SUN, 0);
359 object->updateLight(light);
360 return object->getId();
363 void ClientEnvironment::addActiveObject(u16 id, u8 type,
364 const std::string &init_data)
366 ClientActiveObject* obj =
367 ClientActiveObject::create((ActiveObjectType) type, m_client, this);
370 infostream<<"ClientEnvironment::addActiveObject(): "
371 <<"id="<<id<<" type="<<type<<": Couldn't create object"
380 obj->initialize(init_data);
382 catch(SerializationError &e)
384 errorstream<<"ClientEnvironment::addActiveObject():"
385 <<" id="<<id<<" type="<<type
386 <<": SerializationError in initialize(): "
388 <<": init_data="<<serializeJsonString(init_data)
392 u16 new_id = addActiveObject(obj);
393 // Object initialized:
394 if ((obj = getActiveObject(new_id))) {
395 // Final step is to update all children which are already known
396 // Data provided by GENERIC_CMD_SPAWN_INFANT
397 const auto &children = obj->getAttachmentChildIds();
398 for (auto c_id : children) {
399 if (auto *o = getActiveObject(c_id))
400 o->updateAttachments();
406 void ClientEnvironment::removeActiveObject(u16 id)
408 // Get current attachment childs to detach them visually
409 std::unordered_set<int> attachment_childs;
410 if (auto *obj = getActiveObject(id))
411 attachment_childs = obj->getAttachmentChildIds();
413 m_ao_manager.removeObject(id);
415 // Perform a proper detach in Irrlicht
416 for (auto c_id : attachment_childs) {
417 if (ClientActiveObject *child = getActiveObject(c_id))
418 child->updateAttachments();
422 void ClientEnvironment::processActiveObjectMessage(u16 id, const std::string &data)
424 ClientActiveObject *obj = getActiveObject(id);
426 infostream << "ClientEnvironment::processActiveObjectMessage():"
427 << " got message for id=" << id << ", which doesn't exist."
433 obj->processMessage(data);
434 } catch (SerializationError &e) {
435 errorstream<<"ClientEnvironment::processActiveObjectMessage():"
436 << " id=" << id << " type=" << obj->getType()
437 << " SerializationError in processMessage(): " << e.what()
443 Callbacks for activeobjects
446 void ClientEnvironment::damageLocalPlayer(u16 damage, bool handle_hp)
448 LocalPlayer *lplayer = getLocalPlayer();
452 if (lplayer->hp > damage)
453 lplayer->hp -= damage;
458 ClientEnvEvent event;
459 event.type = CEE_PLAYER_DAMAGE;
460 event.player_damage.amount = damage;
461 event.player_damage.send_to_server = handle_hp;
462 m_client_event_queue.push(event);
466 Client likes to call these
469 ClientEnvEvent ClientEnvironment::getClientEnvEvent()
471 FATAL_ERROR_IF(m_client_event_queue.empty(),
472 "ClientEnvironment::getClientEnvEvent(): queue is empty");
474 ClientEnvEvent event = m_client_event_queue.front();
475 m_client_event_queue.pop();
479 void ClientEnvironment::getSelectedActiveObjects(
480 const core::line3d<f32> &shootline_on_map,
481 std::vector<PointedThing> &objects)
483 std::vector<DistanceSortedActiveObject> allObjects;
484 getActiveObjects(shootline_on_map.start,
485 shootline_on_map.getLength() + 10.0f, allObjects);
486 const v3f line_vector = shootline_on_map.getVector();
488 for (const auto &allObject : allObjects) {
489 ClientActiveObject *obj = allObject.obj;
490 aabb3f selection_box;
491 if (!obj->getSelectionBox(&selection_box))
494 const v3f &pos = obj->getPosition();
495 aabb3f offsetted_box(selection_box.MinEdge + pos,
496 selection_box.MaxEdge + pos);
498 v3f current_intersection;
499 v3s16 current_normal;
500 if (boxLineCollision(offsetted_box, shootline_on_map.start, line_vector,
501 ¤t_intersection, ¤t_normal)) {
502 objects.emplace_back((s16) obj->getId(), current_intersection, current_normal,
503 (current_intersection - shootline_on_map.start).getLengthSQ());