Attachments: Fix attachments to temporary removed objects (#8989)
[oweals/minetest.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 "content_cao.h"
36 #include <algorithm>
37 #include "client/renderingengine.h"
38
39 /*
40         ClientEnvironment
41 */
42
43 ClientEnvironment::ClientEnvironment(ClientMap *map,
44         ITextureSource *texturesource, Client *client):
45         Environment(client),
46         m_map(map),
47         m_texturesource(texturesource),
48         m_client(client)
49 {
50 }
51
52 ClientEnvironment::~ClientEnvironment()
53 {
54         m_ao_manager.clear();
55
56         for (auto &simple_object : m_simple_objects) {
57                 delete simple_object;
58         }
59
60         // Drop/delete map
61         m_map->drop();
62
63         delete m_local_player;
64 }
65
66 Map & ClientEnvironment::getMap()
67 {
68         return *m_map;
69 }
70
71 ClientMap & ClientEnvironment::getClientMap()
72 {
73         return *m_map;
74 }
75
76 void ClientEnvironment::setLocalPlayer(LocalPlayer *player)
77 {
78         /*
79                 It is a failure if already is a local player
80         */
81         FATAL_ERROR_IF(m_local_player != NULL,
82                 "Local player already allocated");
83
84         m_local_player = player;
85 }
86
87 void ClientEnvironment::step(float dtime)
88 {
89         /* Step time of day */
90         stepTimeOfDay(dtime);
91
92         // Get some settings
93         bool fly_allowed = m_client->checkLocalPrivilege("fly");
94         bool free_move = fly_allowed && g_settings->getBool("free_move");
95
96         // Get local player
97         LocalPlayer *lplayer = getLocalPlayer();
98         assert(lplayer);
99         // collision info queue
100         std::vector<CollisionInfo> player_collisions;
101
102         /*
103                 Get the speed the player is going
104         */
105         bool is_climbing = lplayer->is_climbing;
106
107         f32 player_speed = lplayer->getSpeed().getLength();
108
109         /*
110                 Maximum position increment
111         */
112         //f32 position_max_increment = 0.05*BS;
113         f32 position_max_increment = 0.1*BS;
114
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;
120
121         // Maximum time increment is 10ms or lower
122         if(dtime_max_increment > 0.01)
123                 dtime_max_increment = 0.01;
124
125         // Don't allow overly huge dtime
126         if(dtime > 0.5)
127                 dtime = 0.5;
128
129         f32 dtime_downcount = dtime;
130
131         /*
132                 Stuff that has a maximum time increment
133         */
134
135         u32 loopcount = 0;
136         do
137         {
138                 loopcount++;
139
140                 f32 dtime_part;
141                 if(dtime_downcount > dtime_max_increment)
142                 {
143                         dtime_part = dtime_max_increment;
144                         dtime_downcount -= dtime_part;
145                 }
146                 else
147                 {
148                         dtime_part = dtime_downcount;
149                         /*
150                                 Setting this to 0 (no -=dtime_part) disables an infinite loop
151                                 when dtime_part is so small that dtime_downcount -= dtime_part
152                                 does nothing
153                         */
154                         dtime_downcount = 0;
155                 }
156
157                 /*
158                         Handle local player
159                 */
160
161                 {
162                         // Apply physics
163                         if (!free_move && !is_climbing) {
164                                 // Gravity
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;
169
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;
174
175                                 // Liquid resistance
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;
181
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;
186
187                                         dl *= (lplayer->liquid_viscosity * viscosity_factor) +
188                                                 (1 - viscosity_factor);
189                                         v3f d = d_wanted.normalize() * (dl * dtime_part * 100.0f);
190                                         speed += d;
191                                 }
192
193                                 lplayer->setSpeed(speed);
194                         }
195
196                         /*
197                                 Move the lplayer.
198                                 This also does collision detection.
199                         */
200                         lplayer->move(dtime_part, this, position_max_increment,
201                                 &player_collisions);
202                 }
203         } while (dtime_downcount > 0.001);
204
205         bool player_immortal = lplayer->getCAO() && lplayer->getCAO()->isImmortal();
206
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)
212                         continue;
213                 // Get rid of other components
214                 speed_diff.X = 0;
215                 speed_diff.Z = 0;
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->getNode(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;
225                 }
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);
230                         if (damage != 0) {
231                                 damageLocalPlayer(damage, true);
232                                 m_client->getEventManager()->put(
233                                         new SimpleTriggerEvent(MtEvent::PLAYER_FALLING_DAMAGE));
234                         }
235                 }
236         }
237
238         if (m_client->modsLoaded())
239                 m_script->environment_step(dtime);
240
241         // Update lighting on local player (used for wield item)
242         u32 day_night_ratio = getDayNightRatio();
243         {
244                 // Get node at head
245
246                 // On InvalidPositionException, use this as default
247                 // (day: LIGHT_SUN, night: 0)
248                 MapNode node_at_lplayer(CONTENT_AIR, 0x0f, 0);
249
250                 v3s16 p = lplayer->getLightPosition();
251                 node_at_lplayer = m_map->getNode(p);
252
253                 u16 light = getInteriorLight(node_at_lplayer, 0, m_client->ndef());
254                 final_color_blend(&lplayer->light_color, light, day_night_ratio);
255         }
256
257         /*
258                 Step active objects and update lighting of them
259         */
260
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) {
263                 // Step object
264                 cao->step(dtime, this);
265
266                 if (update_lighting) {
267                         // Update lighting
268                         u8 light = 0;
269                         bool pos_ok;
270
271                         // Get node at head
272                         v3s16 p = cao->getLightPosition();
273                         MapNode n = this->m_map->getNode(p, &pos_ok);
274                         if (pos_ok)
275                                 light = n.getLightBlend(day_night_ratio, m_client->ndef());
276                         else
277                                 light = blend_light(day_night_ratio, LIGHT_SUN, 0);
278
279                         cao->updateLight(light);
280                 }
281         };
282
283         m_ao_manager.step(dtime, cb_state);
284
285         /*
286                 Step and handle simple objects
287         */
288         g_profiler->avg("ClientEnv: CSO count [#]", m_simple_objects.size());
289         for (auto i = m_simple_objects.begin(); i != m_simple_objects.end();) {
290                 ClientSimpleObject *simple = *i;
291
292                 simple->step(dtime);
293                 if(simple->m_to_be_removed) {
294                         delete simple;
295                         i = m_simple_objects.erase(i);
296                 }
297                 else {
298                         ++i;
299                 }
300         }
301 }
302
303 void ClientEnvironment::addSimpleObject(ClientSimpleObject *simple)
304 {
305         m_simple_objects.push_back(simple);
306 }
307
308 GenericCAO* ClientEnvironment::getGenericCAO(u16 id)
309 {
310         ClientActiveObject *obj = getActiveObject(id);
311         if (obj && obj->getType() == ACTIVEOBJECT_TYPE_GENERIC)
312                 return (GenericCAO*) obj;
313
314         return NULL;
315 }
316
317 bool isFreeClientActiveObjectId(const u16 id,
318         ClientActiveObjectMap &objects)
319 {
320         return id != 0 && objects.find(id) == objects.end();
321
322 }
323
324 u16 getFreeClientActiveObjectId(ClientActiveObjectMap &objects)
325 {
326         // try to reuse id's as late as possible
327         static u16 last_used_id = 0;
328         u16 startid = last_used_id;
329         for(;;) {
330                 last_used_id ++;
331                 if (isFreeClientActiveObjectId(last_used_id, objects))
332                         return last_used_id;
333
334                 if (last_used_id == startid)
335                         return 0;
336         }
337 }
338
339 u16 ClientEnvironment::addActiveObject(ClientActiveObject *object)
340 {
341         // Register object. If failed return zero id
342         if (!m_ao_manager.registerObject(object))
343                 return 0;
344
345         object->addToScene(m_texturesource);
346
347         // Update lighting immediately
348         u8 light = 0;
349         bool pos_ok;
350
351         // Get node at head
352         v3s16 p = object->getLightPosition();
353         MapNode n = m_map->getNode(p, &pos_ok);
354         if (pos_ok)
355                 light = n.getLightBlend(getDayNightRatio(), m_client->ndef());
356         else
357                 light = blend_light(getDayNightRatio(), LIGHT_SUN, 0);
358
359         object->updateLight(light);
360         return object->getId();
361 }
362
363 void ClientEnvironment::addActiveObject(u16 id, u8 type,
364         const std::string &init_data)
365 {
366         ClientActiveObject* obj =
367                 ClientActiveObject::create((ActiveObjectType) type, m_client, this);
368         if(obj == NULL)
369         {
370                 infostream<<"ClientEnvironment::addActiveObject(): "
371                         <<"id="<<id<<" type="<<type<<": Couldn't create object"
372                         <<std::endl;
373                 return;
374         }
375
376         obj->setId(id);
377
378         try
379         {
380                 obj->initialize(init_data);
381         }
382         catch(SerializationError &e)
383         {
384                 errorstream<<"ClientEnvironment::addActiveObject():"
385                         <<" id="<<id<<" type="<<type
386                         <<": SerializationError in initialize(): "
387                         <<e.what()
388                         <<": init_data="<<serializeJsonString(init_data)
389                         <<std::endl;
390         }
391
392         u16 new_id = addActiveObject(obj);
393         // Object initialized:
394         if ((obj = getActiveObject(new_id))) {
395                 // Final step is to update all children which are already known
396                 // Data provided by GENERIC_CMD_SPAWN_INFANT
397                 const auto &children = obj->getAttachmentChildIds();
398                 for (auto c_id : children) {
399                         if (auto *o = getActiveObject(c_id))
400                                 o->updateAttachments();
401                 }
402         }
403 }
404
405
406 void ClientEnvironment::removeActiveObject(u16 id)
407 {
408         // Get current attachment childs to detach them visually
409         std::unordered_set<int> attachment_childs;
410         if (auto *obj = getActiveObject(id))
411                 attachment_childs = obj->getAttachmentChildIds();
412
413         m_ao_manager.removeObject(id);
414
415         // Perform a proper detach in Irrlicht
416         for (auto c_id : attachment_childs) {
417                 if (ClientActiveObject *child = getActiveObject(c_id))
418                         child->updateAttachments();
419         }
420 }
421
422 void ClientEnvironment::processActiveObjectMessage(u16 id, const std::string &data)
423 {
424         ClientActiveObject *obj = getActiveObject(id);
425         if (obj == NULL) {
426                 infostream << "ClientEnvironment::processActiveObjectMessage():"
427                         << " got message for id=" << id << ", which doesn't exist."
428                         << std::endl;
429                 return;
430         }
431
432         try {
433                 obj->processMessage(data);
434         } catch (SerializationError &e) {
435                 errorstream<<"ClientEnvironment::processActiveObjectMessage():"
436                         << " id=" << id << " type=" << obj->getType()
437                         << " SerializationError in processMessage(): " << e.what()
438                         << std::endl;
439         }
440 }
441
442 /*
443         Callbacks for activeobjects
444 */
445
446 void ClientEnvironment::damageLocalPlayer(u16 damage, bool handle_hp)
447 {
448         LocalPlayer *lplayer = getLocalPlayer();
449         assert(lplayer);
450
451         if (handle_hp) {
452                 if (lplayer->hp > damage)
453                         lplayer->hp -= damage;
454                 else
455                         lplayer->hp = 0;
456         }
457
458         ClientEnvEvent event;
459         event.type = CEE_PLAYER_DAMAGE;
460         event.player_damage.amount = damage;
461         event.player_damage.send_to_server = handle_hp;
462         m_client_event_queue.push(event);
463 }
464
465 /*
466         Client likes to call these
467 */
468
469 ClientEnvEvent ClientEnvironment::getClientEnvEvent()
470 {
471         FATAL_ERROR_IF(m_client_event_queue.empty(),
472                         "ClientEnvironment::getClientEnvEvent(): queue is empty");
473
474         ClientEnvEvent event = m_client_event_queue.front();
475         m_client_event_queue.pop();
476         return event;
477 }
478
479 void ClientEnvironment::getSelectedActiveObjects(
480         const core::line3d<f32> &shootline_on_map,
481         std::vector<PointedThing> &objects)
482 {
483         std::vector<DistanceSortedActiveObject> allObjects;
484         getActiveObjects(shootline_on_map.start,
485                 shootline_on_map.getLength() + 10.0f, allObjects);
486         const v3f line_vector = shootline_on_map.getVector();
487
488         for (const auto &allObject : allObjects) {
489                 ClientActiveObject *obj = allObject.obj;
490                 aabb3f selection_box;
491                 if (!obj->getSelectionBox(&selection_box))
492                         continue;
493
494                 const v3f &pos = obj->getPosition();
495                 aabb3f offsetted_box(selection_box.MinEdge + pos,
496                         selection_box.MaxEdge + pos);
497
498                 v3f current_intersection;
499                 v3s16 current_normal;
500                 if (boxLineCollision(offsetted_box, shootline_on_map.start, line_vector,
501                                 &current_intersection, &current_normal)) {
502                         objects.emplace_back((s16) obj->getId(), current_intersection, current_normal,
503                                 (current_intersection - shootline_on_map.start).getLengthSQ());
504                 }
505         }
506 }