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,
55 bool is_highlevel) override
61 video::SColorf emissive_color(m_emissive_color);
69 m_emissive_color_setting.set(as_array, services);
72 void onSetMaterial(const video::SMaterial& material) override
74 m_emissive_color = material.EmissiveColor;
78 video::SColor m_emissive_color;
79 CachedPixelShaderSetting<float, 4> m_emissive_color_setting;
82 class CAOShaderConstantSetterFactory : public IShaderConstantSetterFactory
85 CAOShaderConstantSetterFactory()
88 virtual IShaderConstantSetter* create()
90 return new CAOShaderConstantSetter();
98 ClientEnvironment::ClientEnvironment(ClientMap *map,
99 ITextureSource *texturesource, Client *client):
102 m_texturesource(texturesource),
105 auto *shdrsrc = m_client->getShaderSource();
106 shdrsrc->addShaderConstantSetterFactory(new CAOShaderConstantSetterFactory());
109 ClientEnvironment::~ClientEnvironment()
111 m_ao_manager.clear();
113 for (auto &simple_object : m_simple_objects) {
114 delete simple_object;
120 delete m_local_player;
123 Map & ClientEnvironment::getMap()
128 ClientMap & ClientEnvironment::getClientMap()
133 void ClientEnvironment::setLocalPlayer(LocalPlayer *player)
136 It is a failure if already is a local player
138 FATAL_ERROR_IF(m_local_player != NULL,
139 "Local player already allocated");
141 m_local_player = player;
144 void ClientEnvironment::step(float dtime)
146 /* Step time of day */
147 stepTimeOfDay(dtime);
150 bool fly_allowed = m_client->checkLocalPrivilege("fly");
151 bool free_move = fly_allowed && g_settings->getBool("free_move");
154 LocalPlayer *lplayer = getLocalPlayer();
156 // collision info queue
157 std::vector<CollisionInfo> player_collisions;
160 Get the speed the player is going
162 bool is_climbing = lplayer->is_climbing;
164 f32 player_speed = lplayer->getSpeed().getLength();
167 Maximum position increment
169 //f32 position_max_increment = 0.05*BS;
170 f32 position_max_increment = 0.1*BS;
172 // Maximum time increment (for collision detection etc)
173 // time = distance / speed
174 f32 dtime_max_increment = 1;
175 if(player_speed > 0.001)
176 dtime_max_increment = position_max_increment / player_speed;
178 // Maximum time increment is 10ms or lower
179 if(dtime_max_increment > 0.01)
180 dtime_max_increment = 0.01;
182 // Don't allow overly huge dtime
186 f32 dtime_downcount = dtime;
189 Stuff that has a maximum time increment
198 if(dtime_downcount > dtime_max_increment)
200 dtime_part = dtime_max_increment;
201 dtime_downcount -= dtime_part;
205 dtime_part = dtime_downcount;
207 Setting this to 0 (no -=dtime_part) disables an infinite loop
208 when dtime_part is so small that dtime_downcount -= dtime_part
220 if (!free_move && !is_climbing) {
222 v3f speed = lplayer->getSpeed();
223 if (!lplayer->in_liquid)
224 speed.Y -= lplayer->movement_gravity *
225 lplayer->physics_override_gravity * dtime_part * 2.0f;
227 // Liquid floating / sinking
228 if (lplayer->in_liquid && !lplayer->swimming_vertical &&
229 !lplayer->swimming_pitch)
230 speed.Y -= lplayer->movement_liquid_sink * dtime_part * 2.0f;
233 if (lplayer->in_liquid_stable || lplayer->in_liquid) {
234 // How much the node's viscosity blocks movement, ranges
235 // between 0 and 1. Should match the scale at which viscosity
236 // increase affects other liquid attributes.
237 static const f32 viscosity_factor = 0.3f;
239 v3f d_wanted = -speed / lplayer->movement_liquid_fluidity;
240 f32 dl = d_wanted.getLength();
241 if (dl > lplayer->movement_liquid_fluidity_smooth)
242 dl = lplayer->movement_liquid_fluidity_smooth;
244 dl *= (lplayer->liquid_viscosity * viscosity_factor) +
245 (1 - viscosity_factor);
246 v3f d = d_wanted.normalize() * (dl * dtime_part * 100.0f);
250 lplayer->setSpeed(speed);
255 This also does collision detection.
257 lplayer->move(dtime_part, this, position_max_increment,
260 } while (dtime_downcount > 0.001);
262 bool player_immortal = lplayer->getCAO() && lplayer->getCAO()->isImmortal();
264 for (const CollisionInfo &info : player_collisions) {
265 v3f speed_diff = info.new_speed - info.old_speed;;
266 // Handle only fall damage
267 // (because otherwise walking against something in fast_move kills you)
268 if (speed_diff.Y < 0 || info.old_speed.Y >= 0)
270 // Get rid of other components
273 f32 pre_factor = 1; // 1 hp per node/s
274 f32 tolerance = BS*14; // 5 without damage
275 f32 post_factor = 1; // 1 hp per node/s
276 if (info.type == COLLISION_NODE) {
277 const ContentFeatures &f = m_client->ndef()->
278 get(m_map->getNode(info.node_p));
279 // Determine fall damage multiplier
280 int addp = itemgroup_get(f.groups, "fall_damage_add_percent");
281 pre_factor = 1.0f + (float)addp / 100.0f;
283 float speed = pre_factor * speed_diff.getLength();
284 if (speed > tolerance && !player_immortal) {
285 f32 damage_f = (speed - tolerance) / BS * post_factor;
286 u16 damage = (u16)MYMIN(damage_f + 0.5, U16_MAX);
288 damageLocalPlayer(damage, true);
289 m_client->getEventManager()->put(
290 new SimpleTriggerEvent(MtEvent::PLAYER_FALLING_DAMAGE));
295 if (m_client->modsLoaded())
296 m_script->environment_step(dtime);
298 // Update lighting on local player (used for wield item)
299 u32 day_night_ratio = getDayNightRatio();
303 // On InvalidPositionException, use this as default
304 // (day: LIGHT_SUN, night: 0)
305 MapNode node_at_lplayer(CONTENT_AIR, 0x0f, 0);
307 v3s16 p = lplayer->getLightPosition();
308 node_at_lplayer = m_map->getNode(p);
310 u16 light = getInteriorLight(node_at_lplayer, 0, m_client->ndef());
311 final_color_blend(&lplayer->light_color, light, day_night_ratio);
315 Step active objects and update lighting of them
318 bool update_lighting = m_active_object_light_update_interval.step(dtime, 0.21);
319 auto cb_state = [this, dtime, update_lighting, day_night_ratio] (ClientActiveObject *cao) {
321 cao->step(dtime, this);
324 cao->updateLight(day_night_ratio);
327 m_ao_manager.step(dtime, cb_state);
330 Step and handle simple objects
332 g_profiler->avg("ClientEnv: CSO count [#]", m_simple_objects.size());
333 for (auto i = m_simple_objects.begin(); i != m_simple_objects.end();) {
334 ClientSimpleObject *simple = *i;
337 if(simple->m_to_be_removed) {
339 i = m_simple_objects.erase(i);
347 void ClientEnvironment::addSimpleObject(ClientSimpleObject *simple)
349 m_simple_objects.push_back(simple);
352 GenericCAO* ClientEnvironment::getGenericCAO(u16 id)
354 ClientActiveObject *obj = getActiveObject(id);
355 if (obj && obj->getType() == ACTIVEOBJECT_TYPE_GENERIC)
356 return (GenericCAO*) obj;
361 bool isFreeClientActiveObjectId(const u16 id,
362 ClientActiveObjectMap &objects)
364 return id != 0 && objects.find(id) == objects.end();
368 u16 getFreeClientActiveObjectId(ClientActiveObjectMap &objects)
370 // try to reuse id's as late as possible
371 static u16 last_used_id = 0;
372 u16 startid = last_used_id;
375 if (isFreeClientActiveObjectId(last_used_id, objects))
378 if (last_used_id == startid)
383 u16 ClientEnvironment::addActiveObject(ClientActiveObject *object)
385 // Register object. If failed return zero id
386 if (!m_ao_manager.registerObject(object))
389 object->addToScene(m_texturesource);
391 // Update lighting immediately
392 object->updateLight(getDayNightRatio());
393 return object->getId();
396 void ClientEnvironment::addActiveObject(u16 id, u8 type,
397 const std::string &init_data)
399 ClientActiveObject* obj =
400 ClientActiveObject::create((ActiveObjectType) type, m_client, this);
403 infostream<<"ClientEnvironment::addActiveObject(): "
404 <<"id="<<id<<" type="<<type<<": Couldn't create object"
413 obj->initialize(init_data);
415 catch(SerializationError &e)
417 errorstream<<"ClientEnvironment::addActiveObject():"
418 <<" id="<<id<<" type="<<type
419 <<": SerializationError in initialize(): "
421 <<": init_data="<<serializeJsonString(init_data)
425 u16 new_id = addActiveObject(obj);
426 // Object initialized:
427 if ((obj = getActiveObject(new_id))) {
428 // Final step is to update all children which are already known
429 // Data provided by AO_CMD_SPAWN_INFANT
430 const auto &children = obj->getAttachmentChildIds();
431 for (auto c_id : children) {
432 if (auto *o = getActiveObject(c_id))
433 o->updateAttachments();
439 void ClientEnvironment::removeActiveObject(u16 id)
441 // Get current attachment childs to detach them visually
442 std::unordered_set<int> attachment_childs;
443 if (auto *obj = getActiveObject(id))
444 attachment_childs = obj->getAttachmentChildIds();
446 m_ao_manager.removeObject(id);
448 // Perform a proper detach in Irrlicht
449 for (auto c_id : attachment_childs) {
450 if (ClientActiveObject *child = getActiveObject(c_id))
451 child->updateAttachments();
455 void ClientEnvironment::processActiveObjectMessage(u16 id, const std::string &data)
457 ClientActiveObject *obj = getActiveObject(id);
459 infostream << "ClientEnvironment::processActiveObjectMessage():"
460 << " got message for id=" << id << ", which doesn't exist."
466 obj->processMessage(data);
467 } catch (SerializationError &e) {
468 errorstream<<"ClientEnvironment::processActiveObjectMessage():"
469 << " id=" << id << " type=" << obj->getType()
470 << " SerializationError in processMessage(): " << e.what()
476 Callbacks for activeobjects
479 void ClientEnvironment::damageLocalPlayer(u16 damage, bool handle_hp)
481 LocalPlayer *lplayer = getLocalPlayer();
485 if (lplayer->hp > damage)
486 lplayer->hp -= damage;
491 ClientEnvEvent event;
492 event.type = CEE_PLAYER_DAMAGE;
493 event.player_damage.amount = damage;
494 event.player_damage.send_to_server = handle_hp;
495 m_client_event_queue.push(event);
499 Client likes to call these
502 ClientEnvEvent ClientEnvironment::getClientEnvEvent()
504 FATAL_ERROR_IF(m_client_event_queue.empty(),
505 "ClientEnvironment::getClientEnvEvent(): queue is empty");
507 ClientEnvEvent event = m_client_event_queue.front();
508 m_client_event_queue.pop();
512 void ClientEnvironment::getSelectedActiveObjects(
513 const core::line3d<f32> &shootline_on_map,
514 std::vector<PointedThing> &objects)
516 std::vector<DistanceSortedActiveObject> allObjects;
517 getActiveObjects(shootline_on_map.start,
518 shootline_on_map.getLength() + 10.0f, allObjects);
519 const v3f line_vector = shootline_on_map.getVector();
521 for (const auto &allObject : allObjects) {
522 ClientActiveObject *obj = allObject.obj;
523 aabb3f selection_box;
524 if (!obj->getSelectionBox(&selection_box))
527 const v3f &pos = obj->getPosition();
528 aabb3f offsetted_box(selection_box.MinEdge + pos,
529 selection_box.MaxEdge + pos);
531 v3f current_intersection;
532 v3s16 current_normal;
533 if (boxLineCollision(offsetted_box, shootline_on_map.start, line_vector,
534 ¤t_intersection, ¤t_normal)) {
535 objects.emplace_back((s16) obj->getId(), current_intersection, current_normal,
536 (current_intersection - shootline_on_map.start).getLengthSQ());