Expose getPointedThing to Lua
[oweals/minetest.git] / src / 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 "clientenvironment.h"
23 #include "clientsimpleobject.h"
24 #include "clientmap.h"
25 #include "scripting_client.h"
26 #include "mapblock_mesh.h"
27 #include "event.h"
28 #include "collision.h"
29 #include "profiler.h"
30 #include "raycast.h"
31 #include "voxelalgorithms.h"
32 #include "settings.h"
33 #include <algorithm>
34 #include "client/renderingengine.h"
35
36 /*
37         ClientEnvironment
38 */
39
40 ClientEnvironment::ClientEnvironment(ClientMap *map,
41         ITextureSource *texturesource, Client *client):
42         Environment(client),
43         m_map(map),
44         m_texturesource(texturesource),
45         m_client(client)
46 {
47         char zero = 0;
48         memset(attachement_parent_ids, zero, sizeof(attachement_parent_ids));
49 }
50
51 ClientEnvironment::~ClientEnvironment()
52 {
53         // delete active objects
54         for (ClientActiveObjectMap::iterator i = m_active_objects.begin();
55                         i != m_active_objects.end(); ++i) {
56                 delete i->second;
57         }
58
59         for(std::vector<ClientSimpleObject*>::iterator
60                 i = m_simple_objects.begin(); i != m_simple_objects.end(); ++i) {
61                 delete *i;
62         }
63
64         // Drop/delete map
65         m_map->drop();
66
67         delete m_local_player;
68 }
69
70 Map & ClientEnvironment::getMap()
71 {
72         return *m_map;
73 }
74
75 ClientMap & ClientEnvironment::getClientMap()
76 {
77         return *m_map;
78 }
79
80 void ClientEnvironment::setLocalPlayer(LocalPlayer *player)
81 {
82         DSTACK(FUNCTION_NAME);
83         /*
84                 It is a failure if already is a local player
85         */
86         FATAL_ERROR_IF(m_local_player != NULL,
87                 "Local player already allocated");
88
89         m_local_player = player;
90 }
91
92 void ClientEnvironment::step(float dtime)
93 {
94         DSTACK(FUNCTION_NAME);
95
96         /* Step time of day */
97         stepTimeOfDay(dtime);
98
99         // Get some settings
100         bool fly_allowed = m_client->checkLocalPrivilege("fly");
101         bool free_move = fly_allowed && g_settings->getBool("free_move");
102
103         // Get local player
104         LocalPlayer *lplayer = getLocalPlayer();
105         assert(lplayer);
106         // collision info queue
107         std::vector<CollisionInfo> player_collisions;
108
109         /*
110                 Get the speed the player is going
111         */
112         bool is_climbing = lplayer->is_climbing;
113
114         f32 player_speed = lplayer->getSpeed().getLength();
115
116         /*
117                 Maximum position increment
118         */
119         //f32 position_max_increment = 0.05*BS;
120         f32 position_max_increment = 0.1*BS;
121
122         // Maximum time increment (for collision detection etc)
123         // time = distance / speed
124         f32 dtime_max_increment = 1;
125         if(player_speed > 0.001)
126                 dtime_max_increment = position_max_increment / player_speed;
127
128         // Maximum time increment is 10ms or lower
129         if(dtime_max_increment > 0.01)
130                 dtime_max_increment = 0.01;
131
132         // Don't allow overly huge dtime
133         if(dtime > 0.5)
134                 dtime = 0.5;
135
136         f32 dtime_downcount = dtime;
137
138         /*
139                 Stuff that has a maximum time increment
140         */
141
142         u32 loopcount = 0;
143         do
144         {
145                 loopcount++;
146
147                 f32 dtime_part;
148                 if(dtime_downcount > dtime_max_increment)
149                 {
150                         dtime_part = dtime_max_increment;
151                         dtime_downcount -= dtime_part;
152                 }
153                 else
154                 {
155                         dtime_part = dtime_downcount;
156                         /*
157                                 Setting this to 0 (no -=dtime_part) disables an infinite loop
158                                 when dtime_part is so small that dtime_downcount -= dtime_part
159                                 does nothing
160                         */
161                         dtime_downcount = 0;
162                 }
163
164                 /*
165                         Handle local player
166                 */
167
168                 {
169                         // Apply physics
170                         if(!free_move && !is_climbing)
171                         {
172                                 // Gravity
173                                 v3f speed = lplayer->getSpeed();
174                                 if(!lplayer->in_liquid)
175                                         speed.Y -= lplayer->movement_gravity * lplayer->physics_override_gravity * dtime_part * 2;
176
177                                 // Liquid floating / sinking
178                                 if(lplayer->in_liquid && !lplayer->swimming_vertical)
179                                         speed.Y -= lplayer->movement_liquid_sink * dtime_part * 2;
180
181                                 // Liquid resistance
182                                 if(lplayer->in_liquid_stable || lplayer->in_liquid)
183                                 {
184                                         // How much the node's viscosity blocks movement, ranges between 0 and 1
185                                         // Should match the scale at which viscosity increase affects other liquid attributes
186                                         const f32 viscosity_factor = 0.3;
187
188                                         v3f d_wanted = -speed / lplayer->movement_liquid_fluidity;
189                                         f32 dl = d_wanted.getLength();
190                                         if(dl > lplayer->movement_liquid_fluidity_smooth)
191                                                 dl = lplayer->movement_liquid_fluidity_smooth;
192                                         dl *= (lplayer->liquid_viscosity * viscosity_factor) + (1 - viscosity_factor);
193
194                                         v3f d = d_wanted.normalize() * dl;
195                                         speed += d;
196                                 }
197
198                                 lplayer->setSpeed(speed);
199                         }
200
201                         /*
202                                 Move the lplayer.
203                                 This also does collision detection.
204                         */
205                         lplayer->move(dtime_part, this, position_max_increment,
206                                 &player_collisions);
207                 }
208         }
209         while(dtime_downcount > 0.001);
210
211         //std::cout<<"Looped "<<loopcount<<" times."<<std::endl;
212
213         for(std::vector<CollisionInfo>::iterator i = player_collisions.begin();
214                 i != player_collisions.end(); ++i) {
215                 CollisionInfo &info = *i;
216                 v3f speed_diff = info.new_speed - info.old_speed;;
217                 // Handle only fall damage
218                 // (because otherwise walking against something in fast_move kills you)
219                 if(speed_diff.Y < 0 || info.old_speed.Y >= 0)
220                         continue;
221                 // Get rid of other components
222                 speed_diff.X = 0;
223                 speed_diff.Z = 0;
224                 f32 pre_factor = 1; // 1 hp per node/s
225                 f32 tolerance = BS*14; // 5 without damage
226                 f32 post_factor = 1; // 1 hp per node/s
227                 if(info.type == COLLISION_NODE)
228                 {
229                         const ContentFeatures &f = m_client->ndef()->
230                                 get(m_map->getNodeNoEx(info.node_p));
231                         // Determine fall damage multiplier
232                         int addp = itemgroup_get(f.groups, "fall_damage_add_percent");
233                         pre_factor = 1.0 + (float)addp/100.0;
234                 }
235                 float speed = pre_factor * speed_diff.getLength();
236                 if (speed > tolerance) {
237                         f32 damage_f = (speed - tolerance) / BS * post_factor;
238                         u8 damage = (u8)MYMIN(damage_f + 0.5, 255);
239                         if (damage != 0) {
240                                 damageLocalPlayer(damage, true);
241                                 MtEvent *e = new SimpleTriggerEvent("PlayerFallingDamage");
242                                 m_client->event()->put(e);
243                         }
244                 }
245         }
246
247         if (m_client->moddingEnabled()) {
248                 m_script->environment_step(dtime);
249         }
250
251         // Protocol v29 make this behaviour obsolete
252         if (getGameDef()->getProtoVersion() < 29) {
253                 if (m_lava_hurt_interval.step(dtime, 1.0)) {
254                         v3f pf = lplayer->getPosition();
255
256                         // Feet, middle and head
257                         v3s16 p1 = floatToInt(pf + v3f(0, BS * 0.1, 0), BS);
258                         MapNode n1 = m_map->getNodeNoEx(p1);
259                         v3s16 p2 = floatToInt(pf + v3f(0, BS * 0.8, 0), BS);
260                         MapNode n2 = m_map->getNodeNoEx(p2);
261                         v3s16 p3 = floatToInt(pf + v3f(0, BS * 1.6, 0), BS);
262                         MapNode n3 = m_map->getNodeNoEx(p3);
263
264                         u32 damage_per_second = 0;
265                         damage_per_second = MYMAX(damage_per_second,
266                                 m_client->ndef()->get(n1).damage_per_second);
267                         damage_per_second = MYMAX(damage_per_second,
268                                 m_client->ndef()->get(n2).damage_per_second);
269                         damage_per_second = MYMAX(damage_per_second,
270                                 m_client->ndef()->get(n3).damage_per_second);
271
272                         if (damage_per_second != 0)
273                                 damageLocalPlayer(damage_per_second, true);
274                 }
275
276                 /*
277                         Drowning
278                 */
279                 if (m_drowning_interval.step(dtime, 2.0)) {
280                         v3f pf = lplayer->getPosition();
281
282                         // head
283                         v3s16 p = floatToInt(pf + v3f(0, BS * 1.6, 0), BS);
284                         MapNode n = m_map->getNodeNoEx(p);
285                         ContentFeatures c = m_client->ndef()->get(n);
286                         u8 drowning_damage = c.drowning;
287                         if (drowning_damage > 0 && lplayer->hp > 0) {
288                                 u16 breath = lplayer->getBreath();
289                                 if (breath > 10) {
290                                         breath = 11;
291                                 }
292                                 if (breath > 0) {
293                                         breath -= 1;
294                                 }
295                                 lplayer->setBreath(breath);
296                                 updateLocalPlayerBreath(breath);
297                         }
298
299                         if (lplayer->getBreath() == 0 && drowning_damage > 0) {
300                                 damageLocalPlayer(drowning_damage, true);
301                         }
302                 }
303                 if (m_breathing_interval.step(dtime, 0.5)) {
304                         v3f pf = lplayer->getPosition();
305
306                         // head
307                         v3s16 p = floatToInt(pf + v3f(0, BS * 1.6, 0), BS);
308                         MapNode n = m_map->getNodeNoEx(p);
309                         ContentFeatures c = m_client->ndef()->get(n);
310                         if (!lplayer->hp) {
311                                 lplayer->setBreath(11);
312                         } else if (c.drowning == 0) {
313                                 u16 breath = lplayer->getBreath();
314                                 if (breath <= 10) {
315                                         breath += 1;
316                                         lplayer->setBreath(breath);
317                                         updateLocalPlayerBreath(breath);
318                                 }
319                         }
320                 }
321         }
322
323         // Update lighting on local player (used for wield item)
324         u32 day_night_ratio = getDayNightRatio();
325         {
326                 // Get node at head
327
328                 // On InvalidPositionException, use this as default
329                 // (day: LIGHT_SUN, night: 0)
330                 MapNode node_at_lplayer(CONTENT_AIR, 0x0f, 0);
331
332                 v3s16 p = lplayer->getLightPosition();
333                 node_at_lplayer = m_map->getNodeNoEx(p);
334
335                 u16 light = getInteriorLight(node_at_lplayer, 0, m_client->ndef());
336                 final_color_blend(&lplayer->light_color, light, day_night_ratio);
337         }
338
339         /*
340                 Step active objects and update lighting of them
341         */
342
343         g_profiler->avg("CEnv: num of objects", m_active_objects.size());
344         bool update_lighting = m_active_object_light_update_interval.step(dtime, 0.21);
345         for (ClientActiveObjectMap::iterator i = m_active_objects.begin();
346                         i != m_active_objects.end(); ++i) {
347                 ClientActiveObject* obj = i->second;
348                 // Step object
349                 obj->step(dtime, this);
350
351                 if(update_lighting)
352                 {
353                         // Update lighting
354                         u8 light = 0;
355                         bool pos_ok;
356
357                         // Get node at head
358                         v3s16 p = obj->getLightPosition();
359                         MapNode n = m_map->getNodeNoEx(p, &pos_ok);
360                         if (pos_ok)
361                                 light = n.getLightBlend(day_night_ratio, m_client->ndef());
362                         else
363                                 light = blend_light(day_night_ratio, LIGHT_SUN, 0);
364
365                         obj->updateLight(light);
366                 }
367         }
368
369         /*
370                 Step and handle simple objects
371         */
372         g_profiler->avg("CEnv: num of simple objects", m_simple_objects.size());
373         for(std::vector<ClientSimpleObject*>::iterator
374                 i = m_simple_objects.begin(); i != m_simple_objects.end();) {
375                 std::vector<ClientSimpleObject*>::iterator cur = i;
376                 ClientSimpleObject *simple = *cur;
377
378                 simple->step(dtime);
379                 if(simple->m_to_be_removed) {
380                         delete simple;
381                         i = m_simple_objects.erase(cur);
382                 }
383                 else {
384                         ++i;
385                 }
386         }
387 }
388
389 void ClientEnvironment::addSimpleObject(ClientSimpleObject *simple)
390 {
391         m_simple_objects.push_back(simple);
392 }
393
394 GenericCAO* ClientEnvironment::getGenericCAO(u16 id)
395 {
396         ClientActiveObject *obj = getActiveObject(id);
397         if (obj && obj->getType() == ACTIVEOBJECT_TYPE_GENERIC)
398                 return (GenericCAO*) obj;
399         else
400                 return NULL;
401 }
402
403 ClientActiveObject* ClientEnvironment::getActiveObject(u16 id)
404 {
405         ClientActiveObjectMap::iterator n = m_active_objects.find(id);
406         if (n == m_active_objects.end())
407                 return NULL;
408         return n->second;
409 }
410
411 bool isFreeClientActiveObjectId(const u16 id,
412         ClientActiveObjectMap &objects)
413 {
414         if(id == 0)
415                 return false;
416
417         return objects.find(id) == objects.end();
418 }
419
420 u16 getFreeClientActiveObjectId(ClientActiveObjectMap &objects)
421 {
422         //try to reuse id's as late as possible
423         static u16 last_used_id = 0;
424         u16 startid = last_used_id;
425         for(;;) {
426                 last_used_id ++;
427                 if (isFreeClientActiveObjectId(last_used_id, objects))
428                         return last_used_id;
429
430                 if (last_used_id == startid)
431                         return 0;
432         }
433 }
434
435 u16 ClientEnvironment::addActiveObject(ClientActiveObject *object)
436 {
437         assert(object); // Pre-condition
438         if(object->getId() == 0)
439         {
440                 u16 new_id = getFreeClientActiveObjectId(m_active_objects);
441                 if(new_id == 0)
442                 {
443                         infostream<<"ClientEnvironment::addActiveObject(): "
444                                 <<"no free ids available"<<std::endl;
445                         delete object;
446                         return 0;
447                 }
448                 object->setId(new_id);
449         }
450         if (!isFreeClientActiveObjectId(object->getId(), m_active_objects)) {
451                 infostream<<"ClientEnvironment::addActiveObject(): "
452                         <<"id is not free ("<<object->getId()<<")"<<std::endl;
453                 delete object;
454                 return 0;
455         }
456         infostream<<"ClientEnvironment::addActiveObject(): "
457                 <<"added (id="<<object->getId()<<")"<<std::endl;
458         m_active_objects[object->getId()] = object;
459         object->addToScene(m_texturesource);
460         { // Update lighting immediately
461                 u8 light = 0;
462                 bool pos_ok;
463
464                 // Get node at head
465                 v3s16 p = object->getLightPosition();
466                 MapNode n = m_map->getNodeNoEx(p, &pos_ok);
467                 if (pos_ok)
468                         light = n.getLightBlend(getDayNightRatio(), m_client->ndef());
469                 else
470                         light = blend_light(getDayNightRatio(), LIGHT_SUN, 0);
471
472                 object->updateLight(light);
473         }
474         return object->getId();
475 }
476
477 void ClientEnvironment::addActiveObject(u16 id, u8 type,
478         const std::string &init_data)
479 {
480         ClientActiveObject* obj =
481                 ClientActiveObject::create((ActiveObjectType) type, m_client, this);
482         if(obj == NULL)
483         {
484                 infostream<<"ClientEnvironment::addActiveObject(): "
485                         <<"id="<<id<<" type="<<type<<": Couldn't create object"
486                         <<std::endl;
487                 return;
488         }
489
490         obj->setId(id);
491
492         try
493         {
494                 obj->initialize(init_data);
495         }
496         catch(SerializationError &e)
497         {
498                 errorstream<<"ClientEnvironment::addActiveObject():"
499                         <<" id="<<id<<" type="<<type
500                         <<": SerializationError in initialize(): "
501                         <<e.what()
502                         <<": init_data="<<serializeJsonString(init_data)
503                         <<std::endl;
504         }
505
506         addActiveObject(obj);
507 }
508
509 void ClientEnvironment::removeActiveObject(u16 id)
510 {
511         verbosestream<<"ClientEnvironment::removeActiveObject(): "
512                 <<"id="<<id<<std::endl;
513         ClientActiveObject* obj = getActiveObject(id);
514         if (obj == NULL) {
515                 infostream<<"ClientEnvironment::removeActiveObject(): "
516                         <<"id="<<id<<" not found"<<std::endl;
517                 return;
518         }
519         obj->removeFromScene(true);
520         delete obj;
521         m_active_objects.erase(id);
522 }
523
524 void ClientEnvironment::processActiveObjectMessage(u16 id, const std::string &data)
525 {
526         ClientActiveObject *obj = getActiveObject(id);
527         if (obj == NULL) {
528                 infostream << "ClientEnvironment::processActiveObjectMessage():"
529                         << " got message for id=" << id << ", which doesn't exist."
530                         << std::endl;
531                 return;
532         }
533
534         try {
535                 obj->processMessage(data);
536         } catch (SerializationError &e) {
537                 errorstream<<"ClientEnvironment::processActiveObjectMessage():"
538                         << " id=" << id << " type=" << obj->getType()
539                         << " SerializationError in processMessage(): " << e.what()
540                         << std::endl;
541         }
542 }
543
544 /*
545         Callbacks for activeobjects
546 */
547
548 void ClientEnvironment::damageLocalPlayer(u8 damage, bool handle_hp)
549 {
550         LocalPlayer *lplayer = getLocalPlayer();
551         assert(lplayer);
552
553         if (handle_hp) {
554                 if (lplayer->hp > damage)
555                         lplayer->hp -= damage;
556                 else
557                         lplayer->hp = 0;
558         }
559
560         ClientEnvEvent event;
561         event.type = CEE_PLAYER_DAMAGE;
562         event.player_damage.amount = damage;
563         event.player_damage.send_to_server = handle_hp;
564         m_client_event_queue.push(event);
565 }
566
567 void ClientEnvironment::updateLocalPlayerBreath(u16 breath)
568 {
569         ClientEnvEvent event;
570         event.type = CEE_PLAYER_BREATH;
571         event.player_breath.amount = breath;
572         m_client_event_queue.push(event);
573 }
574
575 /*
576         Client likes to call these
577 */
578
579 void ClientEnvironment::getActiveObjects(v3f origin, f32 max_d,
580         std::vector<DistanceSortedActiveObject> &dest)
581 {
582         for (ClientActiveObjectMap::iterator i = m_active_objects.begin();
583                         i != m_active_objects.end(); ++i) {
584                 ClientActiveObject* obj = i->second;
585
586                 f32 d = (obj->getPosition() - origin).getLength();
587
588                 if(d > max_d)
589                         continue;
590
591                 DistanceSortedActiveObject dso(obj, d);
592
593                 dest.push_back(dso);
594         }
595 }
596
597 ClientEnvEvent ClientEnvironment::getClientEnvEvent()
598 {
599         FATAL_ERROR_IF(m_client_event_queue.empty(),
600                         "ClientEnvironment::getClientEnvEvent(): queue is empty");
601
602         ClientEnvEvent event = m_client_event_queue.front();
603         m_client_event_queue.pop();
604         return event;
605 }
606
607 void ClientEnvironment::getSelectedActiveObjects(
608         const core::line3d<f32> &shootline_on_map,
609         std::vector<PointedThing> &objects)
610 {
611         std::vector<DistanceSortedActiveObject> allObjects;
612         getActiveObjects(shootline_on_map.start,
613                 shootline_on_map.getLength() + 10.0f, allObjects);
614         const v3f line_vector = shootline_on_map.getVector();
615
616         for (u32 i = 0; i < allObjects.size(); i++) {
617                 ClientActiveObject *obj = allObjects[i].obj;
618                 aabb3f selection_box;
619                 if (!obj->getSelectionBox(&selection_box))
620                         continue;
621                 v3f pos = obj->getPosition();
622                 aabb3f offsetted_box(selection_box.MinEdge + pos,
623                         selection_box.MaxEdge + pos);
624
625                 v3f current_intersection;
626                 v3s16 current_normal;
627                 if (boxLineCollision(offsetted_box, shootline_on_map.start, line_vector,
628                                 &current_intersection, &current_normal)) {
629                         objects.push_back(PointedThing(
630                                 (s16) obj->getId(), current_intersection, current_normal,
631                                 (current_intersection - shootline_on_map.start).getLengthSQ()));
632                 }
633         }
634 }