]> git.lizzy.rs Git - dragonfireclient.git/blob - src/client/clientenvironment.cpp
Add chat_log_level setting (#9223)
[dragonfireclient.git] / src / client / clientenvironment.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2017 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
20 #include "util/serialize.h"
21 #include "util/pointedthing.h"
22 #include "client.h"
23 #include "clientenvironment.h"
24 #include "clientsimpleobject.h"
25 #include "clientmap.h"
26 #include "scripting_client.h"
27 #include "mapblock_mesh.h"
28 #include "event.h"
29 #include "collision.h"
30 #include "nodedef.h"
31 #include "profiler.h"
32 #include "raycast.h"
33 #include "voxelalgorithms.h"
34 #include "settings.h"
35 #include "shader.h"
36 #include "content_cao.h"
37 #include <algorithm>
38 #include "client/renderingengine.h"
39
40 /*
41         CAOShaderConstantSetter
42 */
43
44 //! Shader constant setter for passing material emissive color to the CAO object_shader
45 class CAOShaderConstantSetter : public IShaderConstantSetter
46 {
47 public:
48         CAOShaderConstantSetter():
49                         m_emissive_color_setting("emissiveColor")
50         {}
51
52         ~CAOShaderConstantSetter() override = default;
53
54         void onSetConstants(video::IMaterialRendererServices *services,
55                         bool is_highlevel) override
56         {
57                 if (!is_highlevel)
58                         return;
59
60                 // Ambient color
61                 video::SColorf emissive_color(m_emissive_color);
62
63                 float as_array[4] = {
64                         emissive_color.r,
65                         emissive_color.g,
66                         emissive_color.b,
67                         emissive_color.a,
68                 };
69                 m_emissive_color_setting.set(as_array, services);
70         }
71
72         void onSetMaterial(const video::SMaterial& material) override
73         {
74                 m_emissive_color = material.EmissiveColor;
75         }
76
77 private:
78         video::SColor m_emissive_color;
79         CachedPixelShaderSetting<float, 4> m_emissive_color_setting;
80 };
81
82 class CAOShaderConstantSetterFactory : public IShaderConstantSetterFactory
83 {
84 public:
85         CAOShaderConstantSetterFactory()
86         {}
87
88         virtual IShaderConstantSetter* create()
89         {
90                 return new CAOShaderConstantSetter();
91         }
92 };
93
94 /*
95         ClientEnvironment
96 */
97
98 ClientEnvironment::ClientEnvironment(ClientMap *map,
99         ITextureSource *texturesource, Client *client):
100         Environment(client),
101         m_map(map),
102         m_texturesource(texturesource),
103         m_client(client)
104 {
105         auto *shdrsrc = m_client->getShaderSource();
106         shdrsrc->addShaderConstantSetterFactory(new CAOShaderConstantSetterFactory());
107 }
108
109 ClientEnvironment::~ClientEnvironment()
110 {
111         m_ao_manager.clear();
112
113         for (auto &simple_object : m_simple_objects) {
114                 delete simple_object;
115         }
116
117         // Drop/delete map
118         m_map->drop();
119
120         delete m_local_player;
121 }
122
123 Map & ClientEnvironment::getMap()
124 {
125         return *m_map;
126 }
127
128 ClientMap & ClientEnvironment::getClientMap()
129 {
130         return *m_map;
131 }
132
133 void ClientEnvironment::setLocalPlayer(LocalPlayer *player)
134 {
135         /*
136                 It is a failure if already is a local player
137         */
138         FATAL_ERROR_IF(m_local_player != NULL,
139                 "Local player already allocated");
140
141         m_local_player = player;
142 }
143
144 void ClientEnvironment::step(float dtime)
145 {
146         /* Step time of day */
147         stepTimeOfDay(dtime);
148
149         // Get some settings
150         bool fly_allowed = m_client->checkLocalPrivilege("fly");
151         bool free_move = fly_allowed && g_settings->getBool("free_move");
152
153         // Get local player
154         LocalPlayer *lplayer = getLocalPlayer();
155         assert(lplayer);
156         // collision info queue
157         std::vector<CollisionInfo> player_collisions;
158
159         /*
160                 Get the speed the player is going
161         */
162         bool is_climbing = lplayer->is_climbing;
163
164         f32 player_speed = lplayer->getSpeed().getLength();
165
166         /*
167                 Maximum position increment
168         */
169         //f32 position_max_increment = 0.05*BS;
170         f32 position_max_increment = 0.1*BS;
171
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;
177
178         // Maximum time increment is 10ms or lower
179         if(dtime_max_increment > 0.01)
180                 dtime_max_increment = 0.01;
181
182         // Don't allow overly huge dtime
183         if(dtime > 0.5)
184                 dtime = 0.5;
185
186         f32 dtime_downcount = dtime;
187
188         /*
189                 Stuff that has a maximum time increment
190         */
191
192         u32 loopcount = 0;
193         do
194         {
195                 loopcount++;
196
197                 f32 dtime_part;
198                 if(dtime_downcount > dtime_max_increment)
199                 {
200                         dtime_part = dtime_max_increment;
201                         dtime_downcount -= dtime_part;
202                 }
203                 else
204                 {
205                         dtime_part = dtime_downcount;
206                         /*
207                                 Setting this to 0 (no -=dtime_part) disables an infinite loop
208                                 when dtime_part is so small that dtime_downcount -= dtime_part
209                                 does nothing
210                         */
211                         dtime_downcount = 0;
212                 }
213
214                 /*
215                         Handle local player
216                 */
217
218                 {
219                         // Apply physics
220                         if (!free_move && !is_climbing) {
221                                 // Gravity
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;
226
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;
231
232                                 // Liquid resistance
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;
238
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;
243
244                                         dl *= (lplayer->liquid_viscosity * viscosity_factor) +
245                                                 (1 - viscosity_factor);
246                                         v3f d = d_wanted.normalize() * (dl * dtime_part * 100.0f);
247                                         speed += d;
248                                 }
249
250                                 lplayer->setSpeed(speed);
251                         }
252
253                         /*
254                                 Move the lplayer.
255                                 This also does collision detection.
256                         */
257                         lplayer->move(dtime_part, this, position_max_increment,
258                                 &player_collisions);
259                 }
260         } while (dtime_downcount > 0.001);
261
262         bool player_immortal = lplayer->getCAO() && lplayer->getCAO()->isImmortal();
263
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)
269                         continue;
270                 // Get rid of other components
271                 speed_diff.X = 0;
272                 speed_diff.Z = 0;
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;
282                 }
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);
287                         if (damage != 0) {
288                                 damageLocalPlayer(damage, true);
289                                 m_client->getEventManager()->put(
290                                         new SimpleTriggerEvent(MtEvent::PLAYER_FALLING_DAMAGE));
291                         }
292                 }
293         }
294
295         if (m_client->modsLoaded())
296                 m_script->environment_step(dtime);
297
298         // Update lighting on local player (used for wield item)
299         u32 day_night_ratio = getDayNightRatio();
300         {
301                 // Get node at head
302
303                 // On InvalidPositionException, use this as default
304                 // (day: LIGHT_SUN, night: 0)
305                 MapNode node_at_lplayer(CONTENT_AIR, 0x0f, 0);
306
307                 v3s16 p = lplayer->getLightPosition();
308                 node_at_lplayer = m_map->getNode(p);
309
310                 u16 light = getInteriorLight(node_at_lplayer, 0, m_client->ndef());
311                 final_color_blend(&lplayer->light_color, light, day_night_ratio);
312         }
313
314         /*
315                 Step active objects and update lighting of them
316         */
317
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) {
320                 // Step object
321                 cao->step(dtime, this);
322
323                 if (update_lighting) {
324                         // Update lighting
325                         u8 light = 0;
326                         bool pos_ok;
327
328                         // Get node at head
329                         v3s16 p = cao->getLightPosition();
330                         MapNode n = this->m_map->getNode(p, &pos_ok);
331                         if (pos_ok)
332                                 light = n.getLightBlend(day_night_ratio, m_client->ndef());
333                         else
334                                 light = blend_light(day_night_ratio, LIGHT_SUN, 0);
335
336                         cao->updateLight(light);
337                 }
338         };
339
340         m_ao_manager.step(dtime, cb_state);
341
342         /*
343                 Step and handle simple objects
344         */
345         g_profiler->avg("ClientEnv: CSO count [#]", m_simple_objects.size());
346         for (auto i = m_simple_objects.begin(); i != m_simple_objects.end();) {
347                 ClientSimpleObject *simple = *i;
348
349                 simple->step(dtime);
350                 if(simple->m_to_be_removed) {
351                         delete simple;
352                         i = m_simple_objects.erase(i);
353                 }
354                 else {
355                         ++i;
356                 }
357         }
358 }
359
360 void ClientEnvironment::addSimpleObject(ClientSimpleObject *simple)
361 {
362         m_simple_objects.push_back(simple);
363 }
364
365 GenericCAO* ClientEnvironment::getGenericCAO(u16 id)
366 {
367         ClientActiveObject *obj = getActiveObject(id);
368         if (obj && obj->getType() == ACTIVEOBJECT_TYPE_GENERIC)
369                 return (GenericCAO*) obj;
370
371         return NULL;
372 }
373
374 bool isFreeClientActiveObjectId(const u16 id,
375         ClientActiveObjectMap &objects)
376 {
377         return id != 0 && objects.find(id) == objects.end();
378
379 }
380
381 u16 getFreeClientActiveObjectId(ClientActiveObjectMap &objects)
382 {
383         // try to reuse id's as late as possible
384         static u16 last_used_id = 0;
385         u16 startid = last_used_id;
386         for(;;) {
387                 last_used_id ++;
388                 if (isFreeClientActiveObjectId(last_used_id, objects))
389                         return last_used_id;
390
391                 if (last_used_id == startid)
392                         return 0;
393         }
394 }
395
396 u16 ClientEnvironment::addActiveObject(ClientActiveObject *object)
397 {
398         // Register object. If failed return zero id
399         if (!m_ao_manager.registerObject(object))
400                 return 0;
401
402         object->addToScene(m_texturesource);
403
404         // Update lighting immediately
405         u8 light = 0;
406         bool pos_ok;
407
408         // Get node at head
409         v3s16 p = object->getLightPosition();
410         MapNode n = m_map->getNode(p, &pos_ok);
411         if (pos_ok)
412                 light = n.getLightBlend(getDayNightRatio(), m_client->ndef());
413         else
414                 light = blend_light(getDayNightRatio(), LIGHT_SUN, 0);
415
416         object->updateLight(light);
417         return object->getId();
418 }
419
420 void ClientEnvironment::addActiveObject(u16 id, u8 type,
421         const std::string &init_data)
422 {
423         ClientActiveObject* obj =
424                 ClientActiveObject::create((ActiveObjectType) type, m_client, this);
425         if(obj == NULL)
426         {
427                 infostream<<"ClientEnvironment::addActiveObject(): "
428                         <<"id="<<id<<" type="<<type<<": Couldn't create object"
429                         <<std::endl;
430                 return;
431         }
432
433         obj->setId(id);
434
435         try
436         {
437                 obj->initialize(init_data);
438         }
439         catch(SerializationError &e)
440         {
441                 errorstream<<"ClientEnvironment::addActiveObject():"
442                         <<" id="<<id<<" type="<<type
443                         <<": SerializationError in initialize(): "
444                         <<e.what()
445                         <<": init_data="<<serializeJsonString(init_data)
446                         <<std::endl;
447         }
448
449         u16 new_id = addActiveObject(obj);
450         // Object initialized:
451         if ((obj = getActiveObject(new_id))) {
452                 // Final step is to update all children which are already known
453                 // Data provided by AO_CMD_SPAWN_INFANT
454                 const auto &children = obj->getAttachmentChildIds();
455                 for (auto c_id : children) {
456                         if (auto *o = getActiveObject(c_id))
457                                 o->updateAttachments();
458                 }
459         }
460 }
461
462
463 void ClientEnvironment::removeActiveObject(u16 id)
464 {
465         // Get current attachment childs to detach them visually
466         std::unordered_set<int> attachment_childs;
467         if (auto *obj = getActiveObject(id))
468                 attachment_childs = obj->getAttachmentChildIds();
469
470         m_ao_manager.removeObject(id);
471
472         // Perform a proper detach in Irrlicht
473         for (auto c_id : attachment_childs) {
474                 if (ClientActiveObject *child = getActiveObject(c_id))
475                         child->updateAttachments();
476         }
477 }
478
479 void ClientEnvironment::processActiveObjectMessage(u16 id, const std::string &data)
480 {
481         ClientActiveObject *obj = getActiveObject(id);
482         if (obj == NULL) {
483                 infostream << "ClientEnvironment::processActiveObjectMessage():"
484                         << " got message for id=" << id << ", which doesn't exist."
485                         << std::endl;
486                 return;
487         }
488
489         try {
490                 obj->processMessage(data);
491         } catch (SerializationError &e) {
492                 errorstream<<"ClientEnvironment::processActiveObjectMessage():"
493                         << " id=" << id << " type=" << obj->getType()
494                         << " SerializationError in processMessage(): " << e.what()
495                         << std::endl;
496         }
497 }
498
499 /*
500         Callbacks for activeobjects
501 */
502
503 void ClientEnvironment::damageLocalPlayer(u16 damage, bool handle_hp)
504 {
505         LocalPlayer *lplayer = getLocalPlayer();
506         assert(lplayer);
507
508         if (handle_hp) {
509                 if (lplayer->hp > damage)
510                         lplayer->hp -= damage;
511                 else
512                         lplayer->hp = 0;
513         }
514
515         ClientEnvEvent event;
516         event.type = CEE_PLAYER_DAMAGE;
517         event.player_damage.amount = damage;
518         event.player_damage.send_to_server = handle_hp;
519         m_client_event_queue.push(event);
520 }
521
522 /*
523         Client likes to call these
524 */
525
526 ClientEnvEvent ClientEnvironment::getClientEnvEvent()
527 {
528         FATAL_ERROR_IF(m_client_event_queue.empty(),
529                         "ClientEnvironment::getClientEnvEvent(): queue is empty");
530
531         ClientEnvEvent event = m_client_event_queue.front();
532         m_client_event_queue.pop();
533         return event;
534 }
535
536 void ClientEnvironment::getSelectedActiveObjects(
537         const core::line3d<f32> &shootline_on_map,
538         std::vector<PointedThing> &objects)
539 {
540         std::vector<DistanceSortedActiveObject> allObjects;
541         getActiveObjects(shootline_on_map.start,
542                 shootline_on_map.getLength() + 10.0f, allObjects);
543         const v3f line_vector = shootline_on_map.getVector();
544
545         for (const auto &allObject : allObjects) {
546                 ClientActiveObject *obj = allObject.obj;
547                 aabb3f selection_box;
548                 if (!obj->getSelectionBox(&selection_box))
549                         continue;
550
551                 const v3f &pos = obj->getPosition();
552                 aabb3f offsetted_box(selection_box.MinEdge + pos,
553                         selection_box.MaxEdge + pos);
554
555                 v3f current_intersection;
556                 v3s16 current_normal;
557                 if (boxLineCollision(offsetted_box, shootline_on_map.start, line_vector,
558                                 &current_intersection, &current_normal)) {
559                         objects.emplace_back((s16) obj->getId(), current_intersection, current_normal,
560                                 (current_intersection - shootline_on_map.start).getLengthSQ());
561                 }
562         }
563 }