[CSM] Add enable_client_modding param (default: false)
[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 "clientscripting.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
34 /*
35         ClientEnvironment
36 */
37
38 ClientEnvironment::ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr,
39         ITextureSource *texturesource, Client *client,
40         IrrlichtDevice *irr):
41         m_map(map),
42         m_local_player(NULL),
43         m_smgr(smgr),
44         m_texturesource(texturesource),
45         m_client(client),
46         m_script(NULL),
47         m_irr(irr)
48 {
49         char zero = 0;
50         memset(attachement_parent_ids, zero, sizeof(attachement_parent_ids));
51 }
52
53 ClientEnvironment::~ClientEnvironment()
54 {
55         // delete active objects
56         for (UNORDERED_MAP<u16, ClientActiveObject*>::iterator i = m_active_objects.begin();
57                 i != m_active_objects.end(); ++i) {
58                 delete i->second;
59         }
60
61         for(std::vector<ClientSimpleObject*>::iterator
62                 i = m_simple_objects.begin(); i != m_simple_objects.end(); ++i) {
63                 delete *i;
64         }
65
66         // Drop/delete map
67         m_map->drop();
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                 {
238                         f32 damage_f = (speed - tolerance)/BS * post_factor;
239                         u16 damage = (u16)(damage_f+0.5);
240                         if(damage != 0){
241                                 damageLocalPlayer(damage, true);
242                                 MtEvent *e = new SimpleTriggerEvent("PlayerFallingDamage");
243                                 m_client->event()->put(e);
244                         }
245                 }
246         }
247
248         if (m_client->moddingEnabled()) {
249                 m_script->environment_step(dtime);
250         }
251
252         /*
253                 A quick draft of lava damage
254         */
255         if(m_lava_hurt_interval.step(dtime, 1.0))
256         {
257                 v3f pf = lplayer->getPosition();
258
259                 // Feet, middle and head
260                 v3s16 p1 = floatToInt(pf + v3f(0, BS*0.1, 0), BS);
261                 MapNode n1 = m_map->getNodeNoEx(p1);
262                 v3s16 p2 = floatToInt(pf + v3f(0, BS*0.8, 0), BS);
263                 MapNode n2 = m_map->getNodeNoEx(p2);
264                 v3s16 p3 = floatToInt(pf + v3f(0, BS*1.6, 0), BS);
265                 MapNode n3 = m_map->getNodeNoEx(p3);
266
267                 u32 damage_per_second = 0;
268                 damage_per_second = MYMAX(damage_per_second,
269                         m_client->ndef()->get(n1).damage_per_second);
270                 damage_per_second = MYMAX(damage_per_second,
271                         m_client->ndef()->get(n2).damage_per_second);
272                 damage_per_second = MYMAX(damage_per_second,
273                         m_client->ndef()->get(n3).damage_per_second);
274
275                 if(damage_per_second != 0)
276                 {
277                         damageLocalPlayer(damage_per_second, true);
278                 }
279         }
280
281         // Protocol v29 make this behaviour obsolete
282         if (getGameDef()->getProtoVersion() < 29) {
283                 /*
284                         Drowning
285                 */
286                 if (m_drowning_interval.step(dtime, 2.0)) {
287                         v3f pf = lplayer->getPosition();
288
289                         // head
290                         v3s16 p = floatToInt(pf + v3f(0, BS * 1.6, 0), BS);
291                         MapNode n = m_map->getNodeNoEx(p);
292                         ContentFeatures c = m_client->ndef()->get(n);
293                         u8 drowning_damage = c.drowning;
294                         if (drowning_damage > 0 && lplayer->hp > 0) {
295                                 u16 breath = lplayer->getBreath();
296                                 if (breath > 10) {
297                                         breath = 11;
298                                 }
299                                 if (breath > 0) {
300                                         breath -= 1;
301                                 }
302                                 lplayer->setBreath(breath);
303                                 updateLocalPlayerBreath(breath);
304                         }
305
306                         if (lplayer->getBreath() == 0 && drowning_damage > 0) {
307                                 damageLocalPlayer(drowning_damage, true);
308                         }
309                 }
310                 if (m_breathing_interval.step(dtime, 0.5)) {
311                         v3f pf = lplayer->getPosition();
312
313                         // head
314                         v3s16 p = floatToInt(pf + v3f(0, BS * 1.6, 0), BS);
315                         MapNode n = m_map->getNodeNoEx(p);
316                         ContentFeatures c = m_client->ndef()->get(n);
317                         if (!lplayer->hp) {
318                                 lplayer->setBreath(11);
319                         } else if (c.drowning == 0) {
320                                 u16 breath = lplayer->getBreath();
321                                 if (breath <= 10) {
322                                         breath += 1;
323                                         lplayer->setBreath(breath);
324                                         updateLocalPlayerBreath(breath);
325                                 }
326                         }
327                 }
328         }
329
330         // Update lighting on local player (used for wield item)
331         u32 day_night_ratio = getDayNightRatio();
332         {
333                 // Get node at head
334
335                 // On InvalidPositionException, use this as default
336                 // (day: LIGHT_SUN, night: 0)
337                 MapNode node_at_lplayer(CONTENT_AIR, 0x0f, 0);
338
339                 v3s16 p = lplayer->getLightPosition();
340                 node_at_lplayer = m_map->getNodeNoEx(p);
341
342                 u16 light = getInteriorLight(node_at_lplayer, 0, m_client->ndef());
343                 final_color_blend(&lplayer->light_color, light, day_night_ratio);
344         }
345
346         /*
347                 Step active objects and update lighting of them
348         */
349
350         g_profiler->avg("CEnv: num of objects", m_active_objects.size());
351         bool update_lighting = m_active_object_light_update_interval.step(dtime, 0.21);
352         for (UNORDERED_MAP<u16, ClientActiveObject*>::iterator i = m_active_objects.begin();
353                 i != m_active_objects.end(); ++i) {
354                 ClientActiveObject* obj = i->second;
355                 // Step object
356                 obj->step(dtime, this);
357
358                 if(update_lighting)
359                 {
360                         // Update lighting
361                         u8 light = 0;
362                         bool pos_ok;
363
364                         // Get node at head
365                         v3s16 p = obj->getLightPosition();
366                         MapNode n = m_map->getNodeNoEx(p, &pos_ok);
367                         if (pos_ok)
368                                 light = n.getLightBlend(day_night_ratio, m_client->ndef());
369                         else
370                                 light = blend_light(day_night_ratio, LIGHT_SUN, 0);
371
372                         obj->updateLight(light);
373                 }
374         }
375
376         /*
377                 Step and handle simple objects
378         */
379         g_profiler->avg("CEnv: num of simple objects", m_simple_objects.size());
380         for(std::vector<ClientSimpleObject*>::iterator
381                 i = m_simple_objects.begin(); i != m_simple_objects.end();) {
382                 std::vector<ClientSimpleObject*>::iterator cur = i;
383                 ClientSimpleObject *simple = *cur;
384
385                 simple->step(dtime);
386                 if(simple->m_to_be_removed) {
387                         delete simple;
388                         i = m_simple_objects.erase(cur);
389                 }
390                 else {
391                         ++i;
392                 }
393         }
394 }
395
396 void ClientEnvironment::addSimpleObject(ClientSimpleObject *simple)
397 {
398         m_simple_objects.push_back(simple);
399 }
400
401 GenericCAO* ClientEnvironment::getGenericCAO(u16 id)
402 {
403         ClientActiveObject *obj = getActiveObject(id);
404         if (obj && obj->getType() == ACTIVEOBJECT_TYPE_GENERIC)
405                 return (GenericCAO*) obj;
406         else
407                 return NULL;
408 }
409
410 ClientActiveObject* ClientEnvironment::getActiveObject(u16 id)
411 {
412         UNORDERED_MAP<u16, ClientActiveObject*>::iterator n = m_active_objects.find(id);
413         if (n == m_active_objects.end())
414                 return NULL;
415         return n->second;
416 }
417
418 bool isFreeClientActiveObjectId(const u16 id,
419         UNORDERED_MAP<u16, ClientActiveObject*> &objects)
420 {
421         if(id == 0)
422                 return false;
423
424         return objects.find(id) == objects.end();
425 }
426
427 u16 getFreeClientActiveObjectId(UNORDERED_MAP<u16, ClientActiveObject*> &objects)
428 {
429         //try to reuse id's as late as possible
430         static u16 last_used_id = 0;
431         u16 startid = last_used_id;
432         for(;;) {
433                 last_used_id ++;
434                 if (isFreeClientActiveObjectId(last_used_id, objects))
435                         return last_used_id;
436
437                 if (last_used_id == startid)
438                         return 0;
439         }
440 }
441
442 u16 ClientEnvironment::addActiveObject(ClientActiveObject *object)
443 {
444         assert(object); // Pre-condition
445         if(object->getId() == 0)
446         {
447                 u16 new_id = getFreeClientActiveObjectId(m_active_objects);
448                 if(new_id == 0)
449                 {
450                         infostream<<"ClientEnvironment::addActiveObject(): "
451                                 <<"no free ids available"<<std::endl;
452                         delete object;
453                         return 0;
454                 }
455                 object->setId(new_id);
456         }
457         if (!isFreeClientActiveObjectId(object->getId(), m_active_objects)) {
458                 infostream<<"ClientEnvironment::addActiveObject(): "
459                         <<"id is not free ("<<object->getId()<<")"<<std::endl;
460                 delete object;
461                 return 0;
462         }
463         infostream<<"ClientEnvironment::addActiveObject(): "
464                 <<"added (id="<<object->getId()<<")"<<std::endl;
465         m_active_objects[object->getId()] = object;
466         object->addToScene(m_smgr, m_texturesource, m_irr);
467         { // Update lighting immediately
468                 u8 light = 0;
469                 bool pos_ok;
470
471                 // Get node at head
472                 v3s16 p = object->getLightPosition();
473                 MapNode n = m_map->getNodeNoEx(p, &pos_ok);
474                 if (pos_ok)
475                         light = n.getLightBlend(getDayNightRatio(), m_client->ndef());
476                 else
477                         light = blend_light(getDayNightRatio(), LIGHT_SUN, 0);
478
479                 object->updateLight(light);
480         }
481         return object->getId();
482 }
483
484 void ClientEnvironment::addActiveObject(u16 id, u8 type,
485         const std::string &init_data)
486 {
487         ClientActiveObject* obj =
488                 ClientActiveObject::create((ActiveObjectType) type, m_client, this);
489         if(obj == NULL)
490         {
491                 infostream<<"ClientEnvironment::addActiveObject(): "
492                         <<"id="<<id<<" type="<<type<<": Couldn't create object"
493                         <<std::endl;
494                 return;
495         }
496
497         obj->setId(id);
498
499         try
500         {
501                 obj->initialize(init_data);
502         }
503         catch(SerializationError &e)
504         {
505                 errorstream<<"ClientEnvironment::addActiveObject():"
506                         <<" id="<<id<<" type="<<type
507                         <<": SerializationError in initialize(): "
508                         <<e.what()
509                         <<": init_data="<<serializeJsonString(init_data)
510                         <<std::endl;
511         }
512
513         addActiveObject(obj);
514 }
515
516 void ClientEnvironment::removeActiveObject(u16 id)
517 {
518         verbosestream<<"ClientEnvironment::removeActiveObject(): "
519                 <<"id="<<id<<std::endl;
520         ClientActiveObject* obj = getActiveObject(id);
521         if (obj == NULL) {
522                 infostream<<"ClientEnvironment::removeActiveObject(): "
523                         <<"id="<<id<<" not found"<<std::endl;
524                 return;
525         }
526         obj->removeFromScene(true);
527         delete obj;
528         m_active_objects.erase(id);
529 }
530
531 void ClientEnvironment::processActiveObjectMessage(u16 id, const std::string &data)
532 {
533         ClientActiveObject *obj = getActiveObject(id);
534         if (obj == NULL) {
535                 infostream << "ClientEnvironment::processActiveObjectMessage():"
536                         << " got message for id=" << id << ", which doesn't exist."
537                         << std::endl;
538                 return;
539         }
540
541         try {
542                 obj->processMessage(data);
543         } catch (SerializationError &e) {
544                 errorstream<<"ClientEnvironment::processActiveObjectMessage():"
545                         << " id=" << id << " type=" << obj->getType()
546                         << " SerializationError in processMessage(): " << e.what()
547                         << std::endl;
548         }
549 }
550
551 /*
552         Callbacks for activeobjects
553 */
554
555 void ClientEnvironment::damageLocalPlayer(u8 damage, bool handle_hp)
556 {
557         LocalPlayer *lplayer = getLocalPlayer();
558         assert(lplayer);
559
560         if (handle_hp) {
561                 if (lplayer->hp > damage)
562                         lplayer->hp -= damage;
563                 else
564                         lplayer->hp = 0;
565         }
566
567         ClientEnvEvent event;
568         event.type = CEE_PLAYER_DAMAGE;
569         event.player_damage.amount = damage;
570         event.player_damage.send_to_server = handle_hp;
571         m_client_event_queue.push(event);
572 }
573
574 void ClientEnvironment::updateLocalPlayerBreath(u16 breath)
575 {
576         ClientEnvEvent event;
577         event.type = CEE_PLAYER_BREATH;
578         event.player_breath.amount = breath;
579         m_client_event_queue.push(event);
580 }
581
582 /*
583         Client likes to call these
584 */
585
586 void ClientEnvironment::getActiveObjects(v3f origin, f32 max_d,
587         std::vector<DistanceSortedActiveObject> &dest)
588 {
589         for (UNORDERED_MAP<u16, ClientActiveObject*>::iterator i = m_active_objects.begin();
590                 i != m_active_objects.end(); ++i) {
591                 ClientActiveObject* obj = i->second;
592
593                 f32 d = (obj->getPosition() - origin).getLength();
594
595                 if(d > max_d)
596                         continue;
597
598                 DistanceSortedActiveObject dso(obj, d);
599
600                 dest.push_back(dso);
601         }
602 }
603
604 ClientEnvEvent ClientEnvironment::getClientEvent()
605 {
606         ClientEnvEvent event;
607         if(m_client_event_queue.empty())
608                 event.type = CEE_NONE;
609         else {
610                 event = m_client_event_queue.front();
611                 m_client_event_queue.pop();
612         }
613         return event;
614 }
615
616 ClientActiveObject * ClientEnvironment::getSelectedActiveObject(
617         const core::line3d<f32> &shootline_on_map, v3f *intersection_point,
618         v3s16 *intersection_normal)
619 {
620         std::vector<DistanceSortedActiveObject> objects;
621         getActiveObjects(shootline_on_map.start,
622                 shootline_on_map.getLength() + 3, objects);
623         const v3f line_vector = shootline_on_map.getVector();
624
625         // Sort them.
626         // After this, the closest object is the first in the array.
627         std::sort(objects.begin(), objects.end());
628
629         /* Because objects can have different nodebox sizes,
630          * the object whose center is the nearest isn't necessarily
631          * the closest one. If an object is found, don't stop
632          * immediately. */
633
634         f32 d_min = shootline_on_map.getLength();
635         ClientActiveObject *nearest_obj = NULL;
636         for (u32 i = 0; i < objects.size(); i++) {
637                 ClientActiveObject *obj = objects[i].obj;
638
639                 aabb3f *selection_box = obj->getSelectionBox();
640                 if (selection_box == NULL)
641                         continue;
642
643                 v3f pos = obj->getPosition();
644
645                 aabb3f offsetted_box(selection_box->MinEdge + pos,
646                         selection_box->MaxEdge + pos);
647
648                 if (offsetted_box.getCenter().getDistanceFrom(
649                         shootline_on_map.start) > d_min + 9.6f*BS) {
650                         // Probably there is no active object that has bigger nodebox than
651                         // (-5.5,-5.5,-5.5,5.5,5.5,5.5)
652                         // 9.6 > 5.5*sqrt(3)
653                         break;
654                 }
655
656                 v3f current_intersection;
657                 v3s16 current_normal;
658                 if (boxLineCollision(offsetted_box, shootline_on_map.start, line_vector,
659                         &current_intersection, &current_normal)) {
660                         f32 d_current = current_intersection.getDistanceFrom(
661                                 shootline_on_map.start);
662                         if (d_current <= d_min) {
663                                 d_min = d_current;
664                                 nearest_obj = obj;
665                                 *intersection_point = current_intersection;
666                                 *intersection_normal = current_normal;
667                         }
668                 }
669         }
670
671         return nearest_obj;
672 }
673
674 /*
675         Check if a node is pointable
676 */
677 static inline bool isPointableNode(const MapNode &n,
678         INodeDefManager *ndef, bool liquids_pointable)
679 {
680         const ContentFeatures &features = ndef->get(n);
681         return features.pointable ||
682                 (liquids_pointable && features.isLiquid());
683 }
684
685 PointedThing ClientEnvironment::getPointedThing(
686         core::line3d<f32> shootline,
687         bool liquids_pointable,
688         bool look_for_object)
689 {
690         PointedThing result;
691
692         INodeDefManager *nodedef = m_map->getNodeDefManager();
693
694         core::aabbox3d<s16> maximal_exceed = nodedef->getSelectionBoxIntUnion();
695         // The code needs to search these nodes
696         core::aabbox3d<s16> search_range(-maximal_exceed.MaxEdge,
697                 -maximal_exceed.MinEdge);
698         // If a node is found, there might be a larger node behind.
699         // To find it, we have to go further.
700         s16 maximal_overcheck =
701                 std::max(abs(search_range.MinEdge.X), abs(search_range.MaxEdge.X))
702                         + std::max(abs(search_range.MinEdge.Y), abs(search_range.MaxEdge.Y))
703                         + std::max(abs(search_range.MinEdge.Z), abs(search_range.MaxEdge.Z));
704
705         const v3f original_vector = shootline.getVector();
706         const f32 original_length = original_vector.getLength();
707
708         f32 min_distance = original_length;
709
710         // First try to find an active object
711         if (look_for_object) {
712                 ClientActiveObject *selected_object = getSelectedActiveObject(
713                         shootline, &result.intersection_point,
714                         &result.intersection_normal);
715
716                 if (selected_object != NULL) {
717                         min_distance =
718                                 (result.intersection_point - shootline.start).getLength();
719
720                         result.type = POINTEDTHING_OBJECT;
721                         result.object_id = selected_object->getId();
722                 }
723         }
724
725         // Reduce shootline
726         if (original_length > 0) {
727                 shootline.end = shootline.start
728                         + shootline.getVector() / original_length * min_distance;
729         }
730
731         // Try to find a node that is closer than the selected active
732         // object (if it exists).
733
734         voxalgo::VoxelLineIterator iterator(shootline.start / BS,
735                 shootline.getVector() / BS);
736         v3s16 oldnode = iterator.m_current_node_pos;
737         // Indicates that a node was found.
738         bool is_node_found = false;
739         // If a node is found, it is possible that there's a node
740         // behind it with a large nodebox, so continue the search.
741         u16 node_foundcounter = 0;
742         // If a node is found, this is the center of the
743         // first nodebox the shootline meets.
744         v3f found_boxcenter(0, 0, 0);
745         // The untested nodes are in this range.
746         core::aabbox3d<s16> new_nodes;
747         while (true) {
748                 // Test the nodes around the current node in search_range.
749                 new_nodes = search_range;
750                 new_nodes.MinEdge += iterator.m_current_node_pos;
751                 new_nodes.MaxEdge += iterator.m_current_node_pos;
752
753                 // Only check new nodes
754                 v3s16 delta = iterator.m_current_node_pos - oldnode;
755                 if (delta.X > 0)
756                         new_nodes.MinEdge.X = new_nodes.MaxEdge.X;
757                 else if (delta.X < 0)
758                         new_nodes.MaxEdge.X = new_nodes.MinEdge.X;
759                 else if (delta.Y > 0)
760                         new_nodes.MinEdge.Y = new_nodes.MaxEdge.Y;
761                 else if (delta.Y < 0)
762                         new_nodes.MaxEdge.Y = new_nodes.MinEdge.Y;
763                 else if (delta.Z > 0)
764                         new_nodes.MinEdge.Z = new_nodes.MaxEdge.Z;
765                 else if (delta.Z < 0)
766                         new_nodes.MaxEdge.Z = new_nodes.MinEdge.Z;
767
768                 // For each untested node
769                 for (s16 x = new_nodes.MinEdge.X; x <= new_nodes.MaxEdge.X; x++) {
770                         for (s16 y = new_nodes.MinEdge.Y; y <= new_nodes.MaxEdge.Y; y++) {
771                                 for (s16 z = new_nodes.MinEdge.Z; z <= new_nodes.MaxEdge.Z; z++) {
772                                         MapNode n;
773                                         v3s16 np(x, y, z);
774                                         bool is_valid_position;
775
776                                         n = m_map->getNodeNoEx(np, &is_valid_position);
777                                         if (!(is_valid_position &&
778                                                 isPointableNode(n, nodedef, liquids_pointable))) {
779                                                 continue;
780                                         }
781                                         std::vector<aabb3f> boxes;
782                                         n.getSelectionBoxes(nodedef, &boxes,
783                                                 n.getNeighbors(np, m_map));
784
785                                         v3f npf = intToFloat(np, BS);
786                                         for (std::vector<aabb3f>::const_iterator i = boxes.begin();
787                                                 i != boxes.end(); ++i) {
788                                                 aabb3f box = *i;
789                                                 box.MinEdge += npf;
790                                                 box.MaxEdge += npf;
791                                                 v3f intersection_point;
792                                                 v3s16 intersection_normal;
793                                                 if (!boxLineCollision(box, shootline.start, shootline.getVector(),
794                                                         &intersection_point, &intersection_normal)) {
795                                                         continue;
796                                                 }
797                                                 f32 distance = (intersection_point - shootline.start).getLength();
798                                                 if (distance >= min_distance) {
799                                                         continue;
800                                                 }
801                                                 result.type = POINTEDTHING_NODE;
802                                                 result.node_undersurface = np;
803                                                 result.intersection_point = intersection_point;
804                                                 result.intersection_normal = intersection_normal;
805                                                 found_boxcenter = box.getCenter();
806                                                 min_distance = distance;
807                                                 is_node_found = true;
808                                         }
809                                 }
810                         }
811                 }
812                 if (is_node_found) {
813                         node_foundcounter++;
814                         if (node_foundcounter > maximal_overcheck) {
815                                 break;
816                         }
817                 }
818                 // Next node
819                 if (iterator.hasNext()) {
820                         oldnode = iterator.m_current_node_pos;
821                         iterator.next();
822                 } else {
823                         break;
824                 }
825         }
826
827         if (is_node_found) {
828                 // Set undersurface and abovesurface nodes
829                 f32 d = 0.002 * BS;
830                 v3f fake_intersection = result.intersection_point;
831                 // Move intersection towards its source block.
832                 if (fake_intersection.X < found_boxcenter.X)
833                         fake_intersection.X += d;
834                 else
835                         fake_intersection.X -= d;
836
837                 if (fake_intersection.Y < found_boxcenter.Y)
838                         fake_intersection.Y += d;
839                 else
840                         fake_intersection.Y -= d;
841
842                 if (fake_intersection.Z < found_boxcenter.Z)
843                         fake_intersection.Z += d;
844                 else
845                         fake_intersection.Z -= d;
846
847                 result.node_real_undersurface = floatToInt(fake_intersection, BS);
848                 result.node_abovesurface = result.node_real_undersurface
849                         + result.intersection_normal;
850         }
851         return result;
852 }