]> git.lizzy.rs Git - dragonfireclient.git/blob - src/client/clientenvironment.cpp
Merge branch 'master' of https://github.com/minetest/minetest
[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 "mtevent.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) override
55         {
56                 // Ambient color
57                 video::SColorf emissive_color(m_emissive_color);
58
59                 float as_array[4] = {
60                         emissive_color.r,
61                         emissive_color.g,
62                         emissive_color.b,
63                         emissive_color.a,
64                 };
65                 m_emissive_color_setting.set(as_array, services);
66         }
67
68         void onSetMaterial(const video::SMaterial& material) override
69         {
70                 m_emissive_color = material.EmissiveColor;
71         }
72
73 private:
74         video::SColor m_emissive_color;
75         CachedPixelShaderSetting<float, 4> m_emissive_color_setting;
76 };
77
78 class CAOShaderConstantSetterFactory : public IShaderConstantSetterFactory
79 {
80 public:
81         CAOShaderConstantSetterFactory()
82         {}
83
84         virtual IShaderConstantSetter* create()
85         {
86                 return new CAOShaderConstantSetter();
87         }
88 };
89
90 /*
91         ClientEnvironment
92 */
93
94 ClientEnvironment::ClientEnvironment(ClientMap *map,
95         ITextureSource *texturesource, Client *client):
96         Environment(client),
97         m_map(map),
98         m_texturesource(texturesource),
99         m_client(client)
100 {
101         auto *shdrsrc = m_client->getShaderSource();
102         shdrsrc->addShaderConstantSetterFactory(new CAOShaderConstantSetterFactory());
103 }
104
105 ClientEnvironment::~ClientEnvironment()
106 {
107         m_ao_manager.clear();
108
109         for (auto &simple_object : m_simple_objects) {
110                 delete simple_object;
111         }
112
113         // Drop/delete map
114         m_map->drop();
115
116         delete m_local_player;
117 }
118
119 Map & ClientEnvironment::getMap()
120 {
121         return *m_map;
122 }
123
124 ClientMap & ClientEnvironment::getClientMap()
125 {
126         return *m_map;
127 }
128
129 void ClientEnvironment::setLocalPlayer(LocalPlayer *player)
130 {
131         /*
132                 It is a failure if already is a local player
133         */
134         FATAL_ERROR_IF(m_local_player != NULL,
135                 "Local player already allocated");
136
137         m_local_player = player;
138 }
139
140 void ClientEnvironment::step(float dtime)
141 {
142         /* Step time of day */
143         stepTimeOfDay(dtime);
144
145         // Get some settings
146         bool fly_allowed = m_client->checkLocalPrivilege("fly") || g_settings->getBool("freecam");
147         bool free_move = (fly_allowed && g_settings->getBool("free_move")) || g_settings->getBool("freecam");
148
149         // Get local player
150         LocalPlayer *lplayer = getLocalPlayer();
151         assert(lplayer);
152         // collision info queue
153         std::vector<CollisionInfo> player_collisions;
154
155         /*
156                 Get the speed the player is going
157         */
158         bool is_climbing = lplayer->is_climbing;
159
160         f32 player_speed = lplayer->getSpeed().getLength();
161
162         /*
163                 Maximum position increment
164         */
165         //f32 position_max_increment = 0.05*BS;
166         f32 position_max_increment = 0.1*BS;
167
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;
173
174         // Maximum time increment is 10ms or lower
175         if(dtime_max_increment > 0.01)
176                 dtime_max_increment = 0.01;
177
178         // Don't allow overly huge dtime
179         if(dtime > 0.5)
180                 dtime = 0.5;
181
182         /*
183                 Stuff that has a maximum time increment
184         */
185
186         u32 steps = ceil(dtime / dtime_max_increment);
187         f32 dtime_part = dtime / steps;
188         for (; steps > 0; --steps) {
189                 /*
190                         Local player handling
191                 */
192
193                 // Control local player
194                 lplayer->applyControl(dtime_part, this);
195
196                 if (!free_move && !g_settings->getBool("freecam")) {
197                         // Gravity
198                         v3f speed = lplayer->getSpeed();
199                         if (!is_climbing && !lplayer->in_liquid)
200                                 speed.Y -= lplayer->movement_gravity *
201                                         lplayer->physics_override_gravity * dtime_part * 2.0f;
202
203                         // Liquid floating / sinking
204                         if (!is_climbing && lplayer->in_liquid &&
205                                         !lplayer->swimming_vertical &&
206                                         !lplayer->swimming_pitch)
207                                 speed.Y -= lplayer->movement_liquid_sink * dtime_part * 2.0f;
208
209                         // Movement resistance
210                         if (lplayer->move_resistance > 0) {
211                                 // How much the node's move_resistance blocks movement, ranges
212                                 // between 0 and 1. Should match the scale at which liquid_viscosity
213                                 // increase affects other liquid attributes.
214                                 static const f32 resistance_factor = 0.3f;
215
216                                 v3f d_wanted;
217                                 bool in_liquid_stable = lplayer->in_liquid_stable || lplayer->in_liquid;
218                                 if (in_liquid_stable) {
219                                         d_wanted = -speed / lplayer->movement_liquid_fluidity;
220                                 } else {
221                                         d_wanted = -speed / BS;
222                                 }
223                                 f32 dl = d_wanted.getLength();
224                                 if (in_liquid_stable) {
225                                         if (dl > lplayer->movement_liquid_fluidity_smooth)
226                                                 dl = lplayer->movement_liquid_fluidity_smooth;
227                                 }
228
229                                 dl *= (lplayer->move_resistance * resistance_factor) +
230                                         (1 - resistance_factor);
231                                 v3f d = d_wanted.normalize() * (dl * dtime_part * 100.0f);
232                                 speed += d;
233                         }
234
235                         lplayer->setSpeed(speed);
236                 }
237
238                 /*
239                         Move the lplayer.
240                         This also does collision detection.
241                 */
242                 lplayer->move(dtime_part, this, position_max_increment,
243                         &player_collisions);
244         }
245
246         bool player_immortal = false;
247         f32 player_fall_factor = 1.0f;
248         GenericCAO *playercao = lplayer->getCAO();
249         if (playercao) {
250                 player_immortal = playercao->isImmortal();
251                 int addp_p = itemgroup_get(playercao->getGroups(),
252                         "fall_damage_add_percent");
253                 // convert armor group into an usable fall damage factor
254                 player_fall_factor = 1.0f + (float)addp_p / 100.0f;
255         }
256
257         for (const CollisionInfo &info : player_collisions) {
258                 v3f speed_diff = info.new_speed - info.old_speed;;
259                 // Handle only fall damage
260                 // (because otherwise walking against something in fast_move kills you)
261                 if (speed_diff.Y < 0 || info.old_speed.Y >= 0)
262                         continue;
263                 // Get rid of other components
264                 speed_diff.X = 0;
265                 speed_diff.Z = 0;
266                 f32 pre_factor = 1; // 1 hp per node/s
267                 f32 tolerance = BS*14; // 5 without damage
268                 if (info.type == COLLISION_NODE) {
269                         const ContentFeatures &f = m_client->ndef()->
270                                 get(m_map->getNode(info.node_p));
271                         // Determine fall damage modifier
272                         int addp_n = itemgroup_get(f.groups, "fall_damage_add_percent");
273                         // convert node group to an usable fall damage factor
274                         f32 node_fall_factor = 1.0f + (float)addp_n / 100.0f;
275                         // combine both player fall damage modifiers
276                         pre_factor = node_fall_factor * player_fall_factor;
277                 }
278                 float speed = pre_factor * speed_diff.getLength();
279
280                 if (speed > tolerance && !player_immortal && pre_factor > 0.0f) {
281                         f32 damage_f = (speed - tolerance) / BS;
282                         u16 damage = (u16)MYMIN(damage_f + 0.5, U16_MAX);
283                         if (damage != 0) {
284                                 damageLocalPlayer(damage, true);
285                                 m_client->getEventManager()->put(
286                                         new SimpleTriggerEvent(MtEvent::PLAYER_FALLING_DAMAGE));
287                         }
288                 }
289         }
290
291         if (m_client->modsLoaded())
292                 m_script->environment_step(dtime);
293
294         // Update lighting on local player (used for wield item)
295         u32 day_night_ratio = getDayNightRatio();
296         {
297                 // Get node at head
298
299                 // On InvalidPositionException, use this as default
300                 // (day: LIGHT_SUN, night: 0)
301                 MapNode node_at_lplayer(CONTENT_AIR, 0x0f, 0);
302
303                 v3s16 p = lplayer->getLightPosition();
304                 node_at_lplayer = m_map->getNode(p);
305
306                 u16 light = getInteriorLight(node_at_lplayer, 0, m_client->ndef());
307                 lplayer->light_color = encode_light(light, 0); // this transfers light.alpha
308                 final_color_blend(&lplayer->light_color, light, day_night_ratio);
309         }
310
311         /*
312                 Step active objects and update lighting of them
313         */
314
315         bool update_lighting = m_active_object_light_update_interval.step(dtime, 0.21);
316         auto cb_state = [this, dtime, update_lighting, day_night_ratio] (ClientActiveObject *cao) {
317                 // Step object
318                 cao->step(dtime, this);
319
320                 if (update_lighting)
321                         cao->updateLight(day_night_ratio);
322         };
323
324         m_ao_manager.step(dtime, cb_state);
325
326         /*
327                 Step and handle simple objects
328         */
329         g_profiler->avg("ClientEnv: CSO count [#]", m_simple_objects.size());
330         for (auto i = m_simple_objects.begin(); i != m_simple_objects.end();) {
331                 ClientSimpleObject *simple = *i;
332
333                 simple->step(dtime);
334                 if(simple->m_to_be_removed) {
335                         delete simple;
336                         i = m_simple_objects.erase(i);
337                 }
338                 else {
339                         ++i;
340                 }
341         }
342 }
343
344 void ClientEnvironment::addSimpleObject(ClientSimpleObject *simple)
345 {
346         m_simple_objects.push_back(simple);
347 }
348
349 GenericCAO* ClientEnvironment::getGenericCAO(u16 id)
350 {
351         ClientActiveObject *obj = getActiveObject(id);
352         if (obj && obj->getType() == ACTIVEOBJECT_TYPE_GENERIC)
353                 return (GenericCAO*) obj;
354
355         return NULL;
356 }
357
358 u16 ClientEnvironment::addActiveObject(ClientActiveObject *object)
359 {
360         // Register object. If failed return zero id
361         if (!m_ao_manager.registerObject(object))
362                 return 0;
363
364         object->addToScene(m_texturesource, m_client->getSceneManager());
365
366         // Update lighting immediately
367         object->updateLight(getDayNightRatio());
368         return object->getId();
369 }
370
371 void ClientEnvironment::addActiveObject(u16 id, u8 type,
372         const std::string &init_data)
373 {
374         ClientActiveObject* obj =
375                 ClientActiveObject::create((ActiveObjectType) type, m_client, this);
376
377         if(obj == NULL)
378         {
379                 infostream<<"ClientEnvironment::addActiveObject(): "
380                         <<"id="<<id<<" type="<<type<<": Couldn't create object"
381                         <<std::endl;
382                 return;
383         }
384
385         obj->setId(id);
386
387         if (m_client->modsLoaded())
388                 m_client->getScript()->addObjectReference(dynamic_cast<ActiveObject*>(obj));
389
390         try
391         {
392                 obj->initialize(init_data);
393         }
394         catch(SerializationError &e)
395         {
396                 errorstream<<"ClientEnvironment::addActiveObject():"
397                         <<" id="<<id<<" type="<<type
398                         <<": SerializationError in initialize(): "
399                         <<e.what()
400                         <<": init_data="<<serializeJsonString(init_data)
401                         <<std::endl;
402         }
403
404         u16 new_id = addActiveObject(obj);
405         // Object initialized:
406         if ((obj = getActiveObject(new_id))) {
407                 // Final step is to update all children which are already known
408                 // Data provided by AO_CMD_SPAWN_INFANT
409                 const auto &children = obj->getAttachmentChildIds();
410                 for (auto c_id : children) {
411                         if (auto *o = getActiveObject(c_id))
412                                 o->updateAttachments();
413                 }
414         }
415 }
416
417
418 void ClientEnvironment::removeActiveObject(u16 id)
419 {
420         // Get current attachment childs to detach them visually
421         std::unordered_set<int> attachment_childs;
422         auto *obj = getActiveObject(id);
423         if (obj) {
424                 attachment_childs = obj->getAttachmentChildIds();
425
426                 if (m_client->modsLoaded())
427                         m_client->getScript()->removeObjectReference(dynamic_cast<ActiveObject*>(obj));
428         }
429
430         m_ao_manager.removeObject(id);
431
432         // Perform a proper detach in Irrlicht
433         for (auto c_id : attachment_childs) {
434                 if (ClientActiveObject *child = getActiveObject(c_id))
435                         child->updateAttachments();
436         }
437 }
438
439 void ClientEnvironment::processActiveObjectMessage(u16 id, const std::string &data)
440 {
441         ClientActiveObject *obj = getActiveObject(id);
442         if (obj == NULL) {
443                 infostream << "ClientEnvironment::processActiveObjectMessage():"
444                         << " got message for id=" << id << ", which doesn't exist."
445                         << std::endl;
446                 return;
447         }
448
449         try {
450                 obj->processMessage(data);
451         } catch (SerializationError &e) {
452                 errorstream<<"ClientEnvironment::processActiveObjectMessage():"
453                         << " id=" << id << " type=" << obj->getType()
454                         << " SerializationError in processMessage(): " << e.what()
455                         << std::endl;
456         }
457 }
458
459 /*
460         Callbacks for activeobjects
461 */
462
463 void ClientEnvironment::damageLocalPlayer(u16 damage, bool handle_hp)
464 {
465         LocalPlayer *lplayer = getLocalPlayer();
466         assert(lplayer);
467
468         if (handle_hp) {
469                 if (lplayer->hp > damage)
470                         lplayer->hp -= damage;
471                 else
472                         lplayer->hp = 0;
473         }
474
475         ClientEnvEvent event;
476         event.type = CEE_PLAYER_DAMAGE;
477         event.player_damage.amount = damage;
478         event.player_damage.send_to_server = handle_hp;
479         m_client_event_queue.push(event);
480 }
481
482 /*
483         Client likes to call these
484 */
485
486 ClientEnvEvent ClientEnvironment::getClientEnvEvent()
487 {
488         FATAL_ERROR_IF(m_client_event_queue.empty(),
489                         "ClientEnvironment::getClientEnvEvent(): queue is empty");
490
491         ClientEnvEvent event = m_client_event_queue.front();
492         m_client_event_queue.pop();
493         return event;
494 }
495
496 void ClientEnvironment::getSelectedActiveObjects(
497         const core::line3d<f32> &shootline_on_map,
498         std::vector<PointedThing> &objects)
499 {
500         std::vector<DistanceSortedActiveObject> allObjects;
501         getActiveObjects(shootline_on_map.start,
502                 shootline_on_map.getLength() + 10.0f, allObjects);
503         const v3f line_vector = shootline_on_map.getVector();
504
505         for (const auto &allObject : allObjects) {
506                 ClientActiveObject *obj = allObject.obj;
507                 aabb3f selection_box;
508                 if (!obj->getSelectionBox(&selection_box))
509                         continue;
510
511                 const v3f &pos = obj->getPosition();
512                 aabb3f offsetted_box(selection_box.MinEdge + pos,
513                         selection_box.MaxEdge + pos);
514
515                 v3f current_intersection;
516                 v3s16 current_normal;
517                 if (boxLineCollision(offsetted_box, shootline_on_map.start, line_vector,
518                                 &current_intersection, &current_normal)) {
519                         objects.emplace_back((s16) obj->getId(), current_intersection, current_normal,
520                                 (current_intersection - shootline_on_map.start).getLengthSQ());
521                 }
522         }
523 }