ContentCAO: Fix broken attachments on join (#8701)
[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->getNodeNoEx(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->getNodeNoEx(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->getNodeNoEx(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("CEnv: num of simple objects", m_simple_objects.size());
289         for (auto i = m_simple_objects.begin(); i != m_simple_objects.end();) {
290                 auto cur = i;
291                 ClientSimpleObject *simple = *cur;
292
293                 simple->step(dtime);
294                 if(simple->m_to_be_removed) {
295                         delete simple;
296                         i = m_simple_objects.erase(cur);
297                 }
298                 else {
299                         ++i;
300                 }
301         }
302 }
303
304 void ClientEnvironment::addSimpleObject(ClientSimpleObject *simple)
305 {
306         m_simple_objects.push_back(simple);
307 }
308
309 GenericCAO* ClientEnvironment::getGenericCAO(u16 id)
310 {
311         ClientActiveObject *obj = getActiveObject(id);
312         if (obj && obj->getType() == ACTIVEOBJECT_TYPE_GENERIC)
313                 return (GenericCAO*) obj;
314
315         return NULL;
316 }
317
318 bool isFreeClientActiveObjectId(const u16 id,
319         ClientActiveObjectMap &objects)
320 {
321         return id != 0 && objects.find(id) == objects.end();
322
323 }
324
325 u16 getFreeClientActiveObjectId(ClientActiveObjectMap &objects)
326 {
327         // try to reuse id's as late as possible
328         static u16 last_used_id = 0;
329         u16 startid = last_used_id;
330         for(;;) {
331                 last_used_id ++;
332                 if (isFreeClientActiveObjectId(last_used_id, objects))
333                         return last_used_id;
334
335                 if (last_used_id == startid)
336                         return 0;
337         }
338 }
339
340 u16 ClientEnvironment::addActiveObject(ClientActiveObject *object)
341 {
342         // Register object. If failed return zero id
343         if (!m_ao_manager.registerObject(object))
344                 return 0;
345
346         object->addToScene(m_texturesource);
347
348         // Update lighting immediately
349         u8 light = 0;
350         bool pos_ok;
351
352         // Get node at head
353         v3s16 p = object->getLightPosition();
354         MapNode n = m_map->getNodeNoEx(p, &pos_ok);
355         if (pos_ok)
356                 light = n.getLightBlend(getDayNightRatio(), m_client->ndef());
357         else
358                 light = blend_light(getDayNightRatio(), LIGHT_SUN, 0);
359
360         object->updateLight(light);
361         return object->getId();
362 }
363
364 void ClientEnvironment::addActiveObject(u16 id, u8 type,
365         const std::string &init_data)
366 {
367         ClientActiveObject* obj =
368                 ClientActiveObject::create((ActiveObjectType) type, m_client, this);
369         if(obj == NULL)
370         {
371                 infostream<<"ClientEnvironment::addActiveObject(): "
372                         <<"id="<<id<<" type="<<type<<": Couldn't create object"
373                         <<std::endl;
374                 return;
375         }
376
377         obj->setId(id);
378
379         try
380         {
381                 obj->initialize(init_data);
382         }
383         catch(SerializationError &e)
384         {
385                 errorstream<<"ClientEnvironment::addActiveObject():"
386                         <<" id="<<id<<" type="<<type
387                         <<": SerializationError in initialize(): "
388                         <<e.what()
389                         <<": init_data="<<serializeJsonString(init_data)
390                         <<std::endl;
391         }
392
393         u16 new_id = addActiveObject(obj);
394         // Object initialized:
395         if ((obj = getActiveObject(new_id))) {
396                 // Final step is to update all children which are already known
397                 // Data provided by GENERIC_CMD_SPAWN_INFANT
398                 const auto &children = obj->getAttachmentChildIds();
399                 for (auto c_id : children) {
400                         if (auto *o = getActiveObject(c_id))
401                                 o->updateAttachments();
402                 }
403         }
404 }
405
406 void ClientEnvironment::processActiveObjectMessage(u16 id, const std::string &data)
407 {
408         ClientActiveObject *obj = getActiveObject(id);
409         if (obj == NULL) {
410                 infostream << "ClientEnvironment::processActiveObjectMessage():"
411                         << " got message for id=" << id << ", which doesn't exist."
412                         << std::endl;
413                 return;
414         }
415
416         try {
417                 obj->processMessage(data);
418         } catch (SerializationError &e) {
419                 errorstream<<"ClientEnvironment::processActiveObjectMessage():"
420                         << " id=" << id << " type=" << obj->getType()
421                         << " SerializationError in processMessage(): " << e.what()
422                         << std::endl;
423         }
424 }
425
426 /*
427         Callbacks for activeobjects
428 */
429
430 void ClientEnvironment::damageLocalPlayer(u16 damage, bool handle_hp)
431 {
432         LocalPlayer *lplayer = getLocalPlayer();
433         assert(lplayer);
434
435         if (handle_hp) {
436                 if (lplayer->hp > damage)
437                         lplayer->hp -= damage;
438                 else
439                         lplayer->hp = 0;
440         }
441
442         ClientEnvEvent event;
443         event.type = CEE_PLAYER_DAMAGE;
444         event.player_damage.amount = damage;
445         event.player_damage.send_to_server = handle_hp;
446         m_client_event_queue.push(event);
447 }
448
449 /*
450         Client likes to call these
451 */
452
453 ClientEnvEvent ClientEnvironment::getClientEnvEvent()
454 {
455         FATAL_ERROR_IF(m_client_event_queue.empty(),
456                         "ClientEnvironment::getClientEnvEvent(): queue is empty");
457
458         ClientEnvEvent event = m_client_event_queue.front();
459         m_client_event_queue.pop();
460         return event;
461 }
462
463 void ClientEnvironment::getSelectedActiveObjects(
464         const core::line3d<f32> &shootline_on_map,
465         std::vector<PointedThing> &objects)
466 {
467         std::vector<DistanceSortedActiveObject> allObjects;
468         getActiveObjects(shootline_on_map.start,
469                 shootline_on_map.getLength() + 10.0f, allObjects);
470         const v3f line_vector = shootline_on_map.getVector();
471
472         for (const auto &allObject : allObjects) {
473                 ClientActiveObject *obj = allObject.obj;
474                 aabb3f selection_box;
475                 if (!obj->getSelectionBox(&selection_box))
476                         continue;
477
478                 const v3f &pos = obj->getPosition();
479                 aabb3f offsetted_box(selection_box.MinEdge + pos,
480                         selection_box.MaxEdge + pos);
481
482                 v3f current_intersection;
483                 v3s16 current_normal;
484                 if (boxLineCollision(offsetted_box, shootline_on_map.start, line_vector,
485                                 &current_intersection, &current_normal)) {
486                         objects.emplace_back((s16) obj->getId(), current_intersection, current_normal,
487                                 (current_intersection - shootline_on_map.start).getLengthSQ());
488                 }
489         }
490 }