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->getNodeNoEx(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->getNodeNoEx(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->getNodeNoEx(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("CEnv: num of simple objects", m_simple_objects.size());
289 for (auto i = m_simple_objects.begin(); i != m_simple_objects.end();) {
291 ClientSimpleObject *simple = *cur;
294 if(simple->m_to_be_removed) {
296 i = m_simple_objects.erase(cur);
304 void ClientEnvironment::addSimpleObject(ClientSimpleObject *simple)
306 m_simple_objects.push_back(simple);
309 GenericCAO* ClientEnvironment::getGenericCAO(u16 id)
311 ClientActiveObject *obj = getActiveObject(id);
312 if (obj && obj->getType() == ACTIVEOBJECT_TYPE_GENERIC)
313 return (GenericCAO*) obj;
318 bool isFreeClientActiveObjectId(const u16 id,
319 ClientActiveObjectMap &objects)
321 return id != 0 && objects.find(id) == objects.end();
325 u16 getFreeClientActiveObjectId(ClientActiveObjectMap &objects)
327 // try to reuse id's as late as possible
328 static u16 last_used_id = 0;
329 u16 startid = last_used_id;
332 if (isFreeClientActiveObjectId(last_used_id, objects))
335 if (last_used_id == startid)
340 u16 ClientEnvironment::addActiveObject(ClientActiveObject *object)
342 // Register object. If failed return zero id
343 if (!m_ao_manager.registerObject(object))
346 object->addToScene(m_texturesource);
348 // Update lighting immediately
353 v3s16 p = object->getLightPosition();
354 MapNode n = m_map->getNodeNoEx(p, &pos_ok);
356 light = n.getLightBlend(getDayNightRatio(), m_client->ndef());
358 light = blend_light(getDayNightRatio(), LIGHT_SUN, 0);
360 object->updateLight(light);
361 return object->getId();
364 void ClientEnvironment::addActiveObject(u16 id, u8 type,
365 const std::string &init_data)
367 ClientActiveObject* obj =
368 ClientActiveObject::create((ActiveObjectType) type, m_client, this);
371 infostream<<"ClientEnvironment::addActiveObject(): "
372 <<"id="<<id<<" type="<<type<<": Couldn't create object"
381 obj->initialize(init_data);
383 catch(SerializationError &e)
385 errorstream<<"ClientEnvironment::addActiveObject():"
386 <<" id="<<id<<" type="<<type
387 <<": SerializationError in initialize(): "
389 <<": init_data="<<serializeJsonString(init_data)
393 u16 new_id = addActiveObject(obj);
394 // Object initialized:
395 if ((obj = getActiveObject(new_id))) {
396 // Final step is to update all children which are already known
397 // Data provided by GENERIC_CMD_SPAWN_INFANT
398 const auto &children = obj->getAttachmentChildIds();
399 for (auto c_id : children) {
400 if (auto *o = getActiveObject(c_id))
401 o->updateAttachments();
406 void ClientEnvironment::processActiveObjectMessage(u16 id, const std::string &data)
408 ClientActiveObject *obj = getActiveObject(id);
410 infostream << "ClientEnvironment::processActiveObjectMessage():"
411 << " got message for id=" << id << ", which doesn't exist."
417 obj->processMessage(data);
418 } catch (SerializationError &e) {
419 errorstream<<"ClientEnvironment::processActiveObjectMessage():"
420 << " id=" << id << " type=" << obj->getType()
421 << " SerializationError in processMessage(): " << e.what()
427 Callbacks for activeobjects
430 void ClientEnvironment::damageLocalPlayer(u16 damage, bool handle_hp)
432 LocalPlayer *lplayer = getLocalPlayer();
436 if (lplayer->hp > damage)
437 lplayer->hp -= damage;
442 ClientEnvEvent event;
443 event.type = CEE_PLAYER_DAMAGE;
444 event.player_damage.amount = damage;
445 event.player_damage.send_to_server = handle_hp;
446 m_client_event_queue.push(event);
450 Client likes to call these
453 ClientEnvEvent ClientEnvironment::getClientEnvEvent()
455 FATAL_ERROR_IF(m_client_event_queue.empty(),
456 "ClientEnvironment::getClientEnvEvent(): queue is empty");
458 ClientEnvEvent event = m_client_event_queue.front();
459 m_client_event_queue.pop();
463 void ClientEnvironment::getSelectedActiveObjects(
464 const core::line3d<f32> &shootline_on_map,
465 std::vector<PointedThing> &objects)
467 std::vector<DistanceSortedActiveObject> allObjects;
468 getActiveObjects(shootline_on_map.start,
469 shootline_on_map.getLength() + 10.0f, allObjects);
470 const v3f line_vector = shootline_on_map.getVector();
472 for (const auto &allObject : allObjects) {
473 ClientActiveObject *obj = allObject.obj;
474 aabb3f selection_box;
475 if (!obj->getSelectionBox(&selection_box))
478 const v3f &pos = obj->getPosition();
479 aabb3f offsetted_box(selection_box.MinEdge + pos,
480 selection_box.MaxEdge + pos);
482 v3f current_intersection;
483 v3s16 current_normal;
484 if (boxLineCollision(offsetted_box, shootline_on_map.start, line_vector,
485 ¤t_intersection, ¤t_normal)) {
486 objects.emplace_back((s16) obj->getId(), current_intersection, current_normal,
487 (current_intersection - shootline_on_map.start).getLengthSQ());