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"
36 #include "content_cao.h"
38 #include "client/renderingengine.h"
41 CAOShaderConstantSetter
44 //! Shader constant setter for passing material emissive color to the CAO object_shader
45 class CAOShaderConstantSetter : public IShaderConstantSetter
48 CAOShaderConstantSetter():
49 m_emissive_color_setting("emissiveColor")
52 ~CAOShaderConstantSetter() override = default;
54 void onSetConstants(video::IMaterialRendererServices *services) override
57 video::SColorf emissive_color(m_emissive_color);
65 m_emissive_color_setting.set(as_array, services);
68 void onSetMaterial(const video::SMaterial& material) override
70 m_emissive_color = material.EmissiveColor;
74 video::SColor m_emissive_color;
75 CachedPixelShaderSetting<float, 4> m_emissive_color_setting;
78 class CAOShaderConstantSetterFactory : public IShaderConstantSetterFactory
81 CAOShaderConstantSetterFactory()
84 virtual IShaderConstantSetter* create()
86 return new CAOShaderConstantSetter();
94 ClientEnvironment::ClientEnvironment(ClientMap *map,
95 ITextureSource *texturesource, Client *client):
98 m_texturesource(texturesource),
101 auto *shdrsrc = m_client->getShaderSource();
102 shdrsrc->addShaderConstantSetterFactory(new CAOShaderConstantSetterFactory());
105 ClientEnvironment::~ClientEnvironment()
107 m_ao_manager.clear();
109 for (auto &simple_object : m_simple_objects) {
110 delete simple_object;
116 delete m_local_player;
119 Map & ClientEnvironment::getMap()
124 ClientMap & ClientEnvironment::getClientMap()
129 void ClientEnvironment::setLocalPlayer(LocalPlayer *player)
132 It is a failure if already is a local player
134 FATAL_ERROR_IF(m_local_player != NULL,
135 "Local player already allocated");
137 m_local_player = player;
140 void ClientEnvironment::step(float dtime)
142 /* Step time of day */
143 stepTimeOfDay(dtime);
146 bool fly_allowed = m_client->checkLocalPrivilege("fly");
147 bool free_move = fly_allowed && g_settings->getBool("free_move");
150 LocalPlayer *lplayer = getLocalPlayer();
152 // collision info queue
153 std::vector<CollisionInfo> player_collisions;
156 Get the speed the player is going
158 bool is_climbing = lplayer->is_climbing;
160 f32 player_speed = lplayer->getSpeed().getLength();
163 Maximum position increment
165 //f32 position_max_increment = 0.05*BS;
166 f32 position_max_increment = 0.1*BS;
168 // Maximum time increment (for collision detection etc)
169 // time = distance / speed
170 f32 dtime_max_increment = 1;
171 if(player_speed > 0.001)
172 dtime_max_increment = position_max_increment / player_speed;
174 // Maximum time increment is 10ms or lower
175 if(dtime_max_increment > 0.01)
176 dtime_max_increment = 0.01;
178 // Don't allow overly huge dtime
183 Stuff that has a maximum time increment
186 u32 steps = ceil(dtime / dtime_max_increment);
187 f32 dtime_part = dtime / steps;
188 for (; steps > 0; --steps) {
190 Local player handling
193 // Control local player
194 lplayer->applyControl(dtime_part, this);
199 v3f speed = lplayer->getSpeed();
200 if (!is_climbing && !lplayer->in_liquid)
201 speed.Y -= lplayer->movement_gravity *
202 lplayer->physics_override_gravity * dtime_part * 2.0f;
204 // Liquid floating / sinking
205 if (!is_climbing && lplayer->in_liquid &&
206 !lplayer->swimming_vertical &&
207 !lplayer->swimming_pitch)
208 speed.Y -= lplayer->movement_liquid_sink * dtime_part * 2.0f;
210 // Movement resistance
211 if (lplayer->move_resistance > 0) {
212 // How much the node's move_resistance blocks movement, ranges
213 // between 0 and 1. Should match the scale at which liquid_viscosity
214 // increase affects other liquid attributes.
215 static const f32 resistance_factor = 0.3f;
218 bool in_liquid_stable = lplayer->in_liquid_stable || lplayer->in_liquid;
219 if (in_liquid_stable) {
220 d_wanted = -speed / lplayer->movement_liquid_fluidity;
222 d_wanted = -speed / BS;
224 f32 dl = d_wanted.getLength();
225 if (in_liquid_stable) {
226 if (dl > lplayer->movement_liquid_fluidity_smooth)
227 dl = lplayer->movement_liquid_fluidity_smooth;
230 dl *= (lplayer->move_resistance * resistance_factor) +
231 (1 - resistance_factor);
232 v3f d = d_wanted.normalize() * (dl * dtime_part * 100.0f);
236 lplayer->setSpeed(speed);
241 This also does collision detection.
243 lplayer->move(dtime_part, this, position_max_increment,
247 bool player_immortal = false;
248 f32 player_fall_factor = 1.0f;
249 GenericCAO *playercao = lplayer->getCAO();
251 player_immortal = playercao->isImmortal();
252 int addp_p = itemgroup_get(playercao->getGroups(),
253 "fall_damage_add_percent");
254 // convert armor group into an usable fall damage factor
255 player_fall_factor = 1.0f + (float)addp_p / 100.0f;
258 for (const CollisionInfo &info : player_collisions) {
259 v3f speed_diff = info.new_speed - info.old_speed;;
260 // Handle only fall damage
261 // (because otherwise walking against something in fast_move kills you)
262 if (speed_diff.Y < 0 || info.old_speed.Y >= 0)
264 // Get rid of other components
267 f32 pre_factor = 1; // 1 hp per node/s
268 f32 tolerance = BS*14; // 5 without damage
269 if (info.type == COLLISION_NODE) {
270 const ContentFeatures &f = m_client->ndef()->
271 get(m_map->getNode(info.node_p));
272 // Determine fall damage modifier
273 int addp_n = itemgroup_get(f.groups, "fall_damage_add_percent");
274 // convert node group to an usable fall damage factor
275 f32 node_fall_factor = 1.0f + (float)addp_n / 100.0f;
276 // combine both player fall damage modifiers
277 pre_factor = node_fall_factor * player_fall_factor;
279 float speed = pre_factor * speed_diff.getLength();
281 if (speed > tolerance && !player_immortal && pre_factor > 0.0f) {
282 f32 damage_f = (speed - tolerance) / BS;
283 u16 damage = (u16)MYMIN(damage_f + 0.5, U16_MAX);
285 damageLocalPlayer(damage, true);
286 m_client->getEventManager()->put(
287 new SimpleTriggerEvent(MtEvent::PLAYER_FALLING_DAMAGE));
292 if (m_client->modsLoaded())
293 m_script->environment_step(dtime);
295 // Update lighting on local player (used for wield item)
296 u32 day_night_ratio = getDayNightRatio();
300 // On InvalidPositionException, use this as default
301 // (day: LIGHT_SUN, night: 0)
302 MapNode node_at_lplayer(CONTENT_AIR, 0x0f, 0);
304 v3s16 p = lplayer->getLightPosition();
305 node_at_lplayer = m_map->getNode(p);
307 u16 light = getInteriorLight(node_at_lplayer, 0, m_client->ndef());
308 lplayer->light_color = encode_light(light, 0); // this transfers light.alpha
309 final_color_blend(&lplayer->light_color, light, day_night_ratio);
313 Step active objects and update lighting of them
316 bool update_lighting = m_active_object_light_update_interval.step(dtime, 0.21);
317 auto cb_state = [this, dtime, update_lighting, day_night_ratio] (ClientActiveObject *cao) {
319 cao->step(dtime, this);
322 cao->updateLight(day_night_ratio);
325 m_ao_manager.step(dtime, cb_state);
328 Step and handle simple objects
330 g_profiler->avg("ClientEnv: CSO count [#]", m_simple_objects.size());
331 for (auto i = m_simple_objects.begin(); i != m_simple_objects.end();) {
332 ClientSimpleObject *simple = *i;
335 if(simple->m_to_be_removed) {
337 i = m_simple_objects.erase(i);
345 void ClientEnvironment::addSimpleObject(ClientSimpleObject *simple)
347 m_simple_objects.push_back(simple);
350 GenericCAO* ClientEnvironment::getGenericCAO(u16 id)
352 ClientActiveObject *obj = getActiveObject(id);
353 if (obj && obj->getType() == ACTIVEOBJECT_TYPE_GENERIC)
354 return (GenericCAO*) obj;
359 u16 ClientEnvironment::addActiveObject(ClientActiveObject *object)
361 // Register object. If failed return zero id
362 if (!m_ao_manager.registerObject(object))
365 object->addToScene(m_texturesource, m_client->getSceneManager());
367 // Update lighting immediately
368 object->updateLight(getDayNightRatio());
369 return object->getId();
372 void ClientEnvironment::addActiveObject(u16 id, u8 type,
373 const std::string &init_data)
375 ClientActiveObject* obj =
376 ClientActiveObject::create((ActiveObjectType) type, m_client, this);
379 infostream<<"ClientEnvironment::addActiveObject(): "
380 <<"id="<<id<<" type="<<type<<": Couldn't create object"
389 obj->initialize(init_data);
391 catch(SerializationError &e)
393 errorstream<<"ClientEnvironment::addActiveObject():"
394 <<" id="<<id<<" type="<<type
395 <<": SerializationError in initialize(): "
397 <<": init_data="<<serializeJsonString(init_data)
401 u16 new_id = addActiveObject(obj);
402 // Object initialized:
403 if ((obj = getActiveObject(new_id))) {
404 // Final step is to update all children which are already known
405 // Data provided by AO_CMD_SPAWN_INFANT
406 const auto &children = obj->getAttachmentChildIds();
407 for (auto c_id : children) {
408 if (auto *o = getActiveObject(c_id))
409 o->updateAttachments();
415 void ClientEnvironment::removeActiveObject(u16 id)
417 // Get current attachment childs to detach them visually
418 std::unordered_set<int> attachment_childs;
419 if (auto *obj = getActiveObject(id))
420 attachment_childs = obj->getAttachmentChildIds();
422 m_ao_manager.removeObject(id);
424 // Perform a proper detach in Irrlicht
425 for (auto c_id : attachment_childs) {
426 if (ClientActiveObject *child = getActiveObject(c_id))
427 child->updateAttachments();
431 void ClientEnvironment::processActiveObjectMessage(u16 id, const std::string &data)
433 ClientActiveObject *obj = getActiveObject(id);
435 infostream << "ClientEnvironment::processActiveObjectMessage():"
436 << " got message for id=" << id << ", which doesn't exist."
442 obj->processMessage(data);
443 } catch (SerializationError &e) {
444 errorstream<<"ClientEnvironment::processActiveObjectMessage():"
445 << " id=" << id << " type=" << obj->getType()
446 << " SerializationError in processMessage(): " << e.what()
452 Callbacks for activeobjects
455 void ClientEnvironment::damageLocalPlayer(u16 damage, bool handle_hp)
457 LocalPlayer *lplayer = getLocalPlayer();
461 if (lplayer->hp > damage)
462 lplayer->hp -= damage;
467 ClientEnvEvent event;
468 event.type = CEE_PLAYER_DAMAGE;
469 event.player_damage.amount = damage;
470 event.player_damage.send_to_server = handle_hp;
471 m_client_event_queue.push(event);
475 Client likes to call these
478 ClientEnvEvent ClientEnvironment::getClientEnvEvent()
480 FATAL_ERROR_IF(m_client_event_queue.empty(),
481 "ClientEnvironment::getClientEnvEvent(): queue is empty");
483 ClientEnvEvent event = m_client_event_queue.front();
484 m_client_event_queue.pop();
488 void ClientEnvironment::getSelectedActiveObjects(
489 const core::line3d<f32> &shootline_on_map,
490 std::vector<PointedThing> &objects)
492 std::vector<DistanceSortedActiveObject> allObjects;
493 getActiveObjects(shootline_on_map.start,
494 shootline_on_map.getLength() + 10.0f, allObjects);
495 const v3f line_vector = shootline_on_map.getVector();
497 for (const auto &allObject : allObjects) {
498 ClientActiveObject *obj = allObject.obj;
499 aabb3f selection_box;
500 if (!obj->getSelectionBox(&selection_box))
503 const v3f &pos = obj->getPosition();
504 aabb3f offsetted_box(selection_box.MinEdge + pos,
505 selection_box.MaxEdge + pos);
507 v3f current_intersection;
508 v3s16 current_normal;
509 if (boxLineCollision(offsetted_box, shootline_on_map.start, line_vector,
510 ¤t_intersection, ¤t_normal)) {
511 objects.emplace_back((s16) obj->getId(), current_intersection, current_normal,
512 (current_intersection - shootline_on_map.start).getLengthSQ());