]> git.lizzy.rs Git - minetest.git/blob - src/clientenvironment.cpp
65646c6b4e4ba10975dce04b862edaec2ad79117
[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 "mapblock_mesh.h"
26 #include "event.h"
27 #include "collision.h"
28 #include "profiler.h"
29 #include "raycast.h"
30 #include "voxelalgorithms.h"
31
32 /*
33         ClientEnvironment
34 */
35
36 ClientEnvironment::ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr,
37         ITextureSource *texturesource, Client *client,
38         IrrlichtDevice *irr):
39         m_map(map),
40         m_local_player(NULL),
41         m_smgr(smgr),
42         m_texturesource(texturesource),
43         m_client(client),
44         m_irr(irr)
45 {
46         char zero = 0;
47         memset(attachement_parent_ids, zero, sizeof(attachement_parent_ids));
48 }
49
50 ClientEnvironment::~ClientEnvironment()
51 {
52         // delete active objects
53         for (UNORDERED_MAP<u16, ClientActiveObject*>::iterator i = m_active_objects.begin();
54                 i != m_active_objects.end(); ++i) {
55                 delete i->second;
56         }
57
58         for(std::vector<ClientSimpleObject*>::iterator
59                 i = m_simple_objects.begin(); i != m_simple_objects.end(); ++i) {
60                 delete *i;
61         }
62
63         // Drop/delete map
64         m_map->drop();
65 }
66
67 Map & ClientEnvironment::getMap()
68 {
69         return *m_map;
70 }
71
72 ClientMap & ClientEnvironment::getClientMap()
73 {
74         return *m_map;
75 }
76
77 void ClientEnvironment::setLocalPlayer(LocalPlayer *player)
78 {
79         DSTACK(FUNCTION_NAME);
80         /*
81                 It is a failure if already is a local player
82         */
83         FATAL_ERROR_IF(m_local_player != NULL,
84                 "Local player already allocated");
85
86         m_local_player = player;
87 }
88
89 void ClientEnvironment::step(float dtime)
90 {
91         DSTACK(FUNCTION_NAME);
92
93         /* Step time of day */
94         stepTimeOfDay(dtime);
95
96         // Get some settings
97         bool fly_allowed = m_client->checkLocalPrivilege("fly");
98         bool free_move = fly_allowed && g_settings->getBool("free_move");
99
100         // Get local player
101         LocalPlayer *lplayer = getLocalPlayer();
102         assert(lplayer);
103         // collision info queue
104         std::vector<CollisionInfo> player_collisions;
105
106         /*
107                 Get the speed the player is going
108         */
109         bool is_climbing = lplayer->is_climbing;
110
111         f32 player_speed = lplayer->getSpeed().getLength();
112
113         /*
114                 Maximum position increment
115         */
116         //f32 position_max_increment = 0.05*BS;
117         f32 position_max_increment = 0.1*BS;
118
119         // Maximum time increment (for collision detection etc)
120         // time = distance / speed
121         f32 dtime_max_increment = 1;
122         if(player_speed > 0.001)
123                 dtime_max_increment = position_max_increment / player_speed;
124
125         // Maximum time increment is 10ms or lower
126         if(dtime_max_increment > 0.01)
127                 dtime_max_increment = 0.01;
128
129         // Don't allow overly huge dtime
130         if(dtime > 0.5)
131                 dtime = 0.5;
132
133         f32 dtime_downcount = dtime;
134
135         /*
136                 Stuff that has a maximum time increment
137         */
138
139         u32 loopcount = 0;
140         do
141         {
142                 loopcount++;
143
144                 f32 dtime_part;
145                 if(dtime_downcount > dtime_max_increment)
146                 {
147                         dtime_part = dtime_max_increment;
148                         dtime_downcount -= dtime_part;
149                 }
150                 else
151                 {
152                         dtime_part = dtime_downcount;
153                         /*
154                                 Setting this to 0 (no -=dtime_part) disables an infinite loop
155                                 when dtime_part is so small that dtime_downcount -= dtime_part
156                                 does nothing
157                         */
158                         dtime_downcount = 0;
159                 }
160
161                 /*
162                         Handle local player
163                 */
164
165                 {
166                         // Apply physics
167                         if(!free_move && !is_climbing)
168                         {
169                                 // Gravity
170                                 v3f speed = lplayer->getSpeed();
171                                 if(!lplayer->in_liquid)
172                                         speed.Y -= lplayer->movement_gravity * lplayer->physics_override_gravity * dtime_part * 2;
173
174                                 // Liquid floating / sinking
175                                 if(lplayer->in_liquid && !lplayer->swimming_vertical)
176                                         speed.Y -= lplayer->movement_liquid_sink * dtime_part * 2;
177
178                                 // Liquid resistance
179                                 if(lplayer->in_liquid_stable || lplayer->in_liquid)
180                                 {
181                                         // How much the node's viscosity blocks movement, ranges between 0 and 1
182                                         // Should match the scale at which viscosity increase affects other liquid attributes
183                                         const f32 viscosity_factor = 0.3;
184
185                                         v3f d_wanted = -speed / lplayer->movement_liquid_fluidity;
186                                         f32 dl = d_wanted.getLength();
187                                         if(dl > lplayer->movement_liquid_fluidity_smooth)
188                                                 dl = lplayer->movement_liquid_fluidity_smooth;
189                                         dl *= (lplayer->liquid_viscosity * viscosity_factor) + (1 - viscosity_factor);
190
191                                         v3f d = d_wanted.normalize() * dl;
192                                         speed += d;
193                                 }
194
195                                 lplayer->setSpeed(speed);
196                         }
197
198                         /*
199                                 Move the lplayer.
200                                 This also does collision detection.
201                         */
202                         lplayer->move(dtime_part, this, position_max_increment,
203                                 &player_collisions);
204                 }
205         }
206         while(dtime_downcount > 0.001);
207
208         //std::cout<<"Looped "<<loopcount<<" times."<<std::endl;
209
210         for(std::vector<CollisionInfo>::iterator i = player_collisions.begin();
211                 i != player_collisions.end(); ++i) {
212                 CollisionInfo &info = *i;
213                 v3f speed_diff = info.new_speed - info.old_speed;;
214                 // Handle only fall damage
215                 // (because otherwise walking against something in fast_move kills you)
216                 if(speed_diff.Y < 0 || info.old_speed.Y >= 0)
217                         continue;
218                 // Get rid of other components
219                 speed_diff.X = 0;
220                 speed_diff.Z = 0;
221                 f32 pre_factor = 1; // 1 hp per node/s
222                 f32 tolerance = BS*14; // 5 without damage
223                 f32 post_factor = 1; // 1 hp per node/s
224                 if(info.type == COLLISION_NODE)
225                 {
226                         const ContentFeatures &f = m_client->ndef()->
227                                 get(m_map->getNodeNoEx(info.node_p));
228                         // Determine fall damage multiplier
229                         int addp = itemgroup_get(f.groups, "fall_damage_add_percent");
230                         pre_factor = 1.0 + (float)addp/100.0;
231                 }
232                 float speed = pre_factor * speed_diff.getLength();
233                 if(speed > tolerance)
234                 {
235                         f32 damage_f = (speed - tolerance)/BS * post_factor;
236                         u16 damage = (u16)(damage_f+0.5);
237                         if(damage != 0){
238                                 damageLocalPlayer(damage, true);
239                                 MtEvent *e = new SimpleTriggerEvent("PlayerFallingDamage");
240                                 m_client->event()->put(e);
241                         }
242                 }
243         }
244
245         /*
246                 A quick draft of lava damage
247         */
248         if(m_lava_hurt_interval.step(dtime, 1.0))
249         {
250                 v3f pf = lplayer->getPosition();
251
252                 // Feet, middle and head
253                 v3s16 p1 = floatToInt(pf + v3f(0, BS*0.1, 0), BS);
254                 MapNode n1 = m_map->getNodeNoEx(p1);
255                 v3s16 p2 = floatToInt(pf + v3f(0, BS*0.8, 0), BS);
256                 MapNode n2 = m_map->getNodeNoEx(p2);
257                 v3s16 p3 = floatToInt(pf + v3f(0, BS*1.6, 0), BS);
258                 MapNode n3 = m_map->getNodeNoEx(p3);
259
260                 u32 damage_per_second = 0;
261                 damage_per_second = MYMAX(damage_per_second,
262                         m_client->ndef()->get(n1).damage_per_second);
263                 damage_per_second = MYMAX(damage_per_second,
264                         m_client->ndef()->get(n2).damage_per_second);
265                 damage_per_second = MYMAX(damage_per_second,
266                         m_client->ndef()->get(n3).damage_per_second);
267
268                 if(damage_per_second != 0)
269                 {
270                         damageLocalPlayer(damage_per_second, true);
271                 }
272         }
273
274         // Protocol v29 make this behaviour obsolete
275         if (getGameDef()->getProtoVersion() < 29) {
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                 u8 day = light & 0xff;
337                 u8 night = (light >> 8) & 0xff;
338                 finalColorBlend(lplayer->light_color, day, night, day_night_ratio);
339         }
340
341         /*
342                 Step active objects and update lighting of them
343         */
344
345         g_profiler->avg("CEnv: num of objects", m_active_objects.size());
346         bool update_lighting = m_active_object_light_update_interval.step(dtime, 0.21);
347         for (UNORDERED_MAP<u16, ClientActiveObject*>::iterator i = m_active_objects.begin();
348                 i != m_active_objects.end(); ++i) {
349                 ClientActiveObject* obj = i->second;
350                 // Step object
351                 obj->step(dtime, this);
352
353                 if(update_lighting)
354                 {
355                         // Update lighting
356                         u8 light = 0;
357                         bool pos_ok;
358
359                         // Get node at head
360                         v3s16 p = obj->getLightPosition();
361                         MapNode n = m_map->getNodeNoEx(p, &pos_ok);
362                         if (pos_ok)
363                                 light = n.getLightBlend(day_night_ratio, m_client->ndef());
364                         else
365                                 light = blend_light(day_night_ratio, LIGHT_SUN, 0);
366
367                         obj->updateLight(light);
368                 }
369         }
370
371         /*
372                 Step and handle simple objects
373         */
374         g_profiler->avg("CEnv: num of simple objects", m_simple_objects.size());
375         for(std::vector<ClientSimpleObject*>::iterator
376                 i = m_simple_objects.begin(); i != m_simple_objects.end();) {
377                 std::vector<ClientSimpleObject*>::iterator cur = i;
378                 ClientSimpleObject *simple = *cur;
379
380                 simple->step(dtime);
381                 if(simple->m_to_be_removed) {
382                         delete simple;
383                         i = m_simple_objects.erase(cur);
384                 }
385                 else {
386                         ++i;
387                 }
388         }
389 }
390
391 void ClientEnvironment::addSimpleObject(ClientSimpleObject *simple)
392 {
393         m_simple_objects.push_back(simple);
394 }
395
396 GenericCAO* ClientEnvironment::getGenericCAO(u16 id)
397 {
398         ClientActiveObject *obj = getActiveObject(id);
399         if (obj && obj->getType() == ACTIVEOBJECT_TYPE_GENERIC)
400                 return (GenericCAO*) obj;
401         else
402                 return NULL;
403 }
404
405 ClientActiveObject* ClientEnvironment::getActiveObject(u16 id)
406 {
407         UNORDERED_MAP<u16, ClientActiveObject*>::iterator n = m_active_objects.find(id);
408         if (n == m_active_objects.end())
409                 return NULL;
410         return n->second;
411 }
412
413 bool isFreeClientActiveObjectId(const u16 id,
414         UNORDERED_MAP<u16, ClientActiveObject*> &objects)
415 {
416         if(id == 0)
417                 return false;
418
419         return objects.find(id) == objects.end();
420 }
421
422 u16 getFreeClientActiveObjectId(UNORDERED_MAP<u16, ClientActiveObject*> &objects)
423 {
424         //try to reuse id's as late as possible
425         static u16 last_used_id = 0;
426         u16 startid = last_used_id;
427         for(;;) {
428                 last_used_id ++;
429                 if (isFreeClientActiveObjectId(last_used_id, objects))
430                         return last_used_id;
431
432                 if (last_used_id == startid)
433                         return 0;
434         }
435 }
436
437 u16 ClientEnvironment::addActiveObject(ClientActiveObject *object)
438 {
439         assert(object); // Pre-condition
440         if(object->getId() == 0)
441         {
442                 u16 new_id = getFreeClientActiveObjectId(m_active_objects);
443                 if(new_id == 0)
444                 {
445                         infostream<<"ClientEnvironment::addActiveObject(): "
446                                 <<"no free ids available"<<std::endl;
447                         delete object;
448                         return 0;
449                 }
450                 object->setId(new_id);
451         }
452         if (!isFreeClientActiveObjectId(object->getId(), m_active_objects)) {
453                 infostream<<"ClientEnvironment::addActiveObject(): "
454                         <<"id is not free ("<<object->getId()<<")"<<std::endl;
455                 delete object;
456                 return 0;
457         }
458         infostream<<"ClientEnvironment::addActiveObject(): "
459                 <<"added (id="<<object->getId()<<")"<<std::endl;
460         m_active_objects[object->getId()] = object;
461         object->addToScene(m_smgr, m_texturesource, m_irr);
462         { // Update lighting immediately
463                 u8 light = 0;
464                 bool pos_ok;
465
466                 // Get node at head
467                 v3s16 p = object->getLightPosition();
468                 MapNode n = m_map->getNodeNoEx(p, &pos_ok);
469                 if (pos_ok)
470                         light = n.getLightBlend(getDayNightRatio(), m_client->ndef());
471                 else
472                         light = blend_light(getDayNightRatio(), LIGHT_SUN, 0);
473
474                 object->updateLight(light);
475         }
476         return object->getId();
477 }
478
479 void ClientEnvironment::addActiveObject(u16 id, u8 type,
480         const std::string &init_data)
481 {
482         ClientActiveObject* obj =
483                 ClientActiveObject::create((ActiveObjectType) type, m_client, this);
484         if(obj == NULL)
485         {
486                 infostream<<"ClientEnvironment::addActiveObject(): "
487                         <<"id="<<id<<" type="<<type<<": Couldn't create object"
488                         <<std::endl;
489                 return;
490         }
491
492         obj->setId(id);
493
494         try
495         {
496                 obj->initialize(init_data);
497         }
498         catch(SerializationError &e)
499         {
500                 errorstream<<"ClientEnvironment::addActiveObject():"
501                         <<" id="<<id<<" type="<<type
502                         <<": SerializationError in initialize(): "
503                         <<e.what()
504                         <<": init_data="<<serializeJsonString(init_data)
505                         <<std::endl;
506         }
507
508         addActiveObject(obj);
509 }
510
511 void ClientEnvironment::removeActiveObject(u16 id)
512 {
513         verbosestream<<"ClientEnvironment::removeActiveObject(): "
514                 <<"id="<<id<<std::endl;
515         ClientActiveObject* obj = getActiveObject(id);
516         if (obj == NULL) {
517                 infostream<<"ClientEnvironment::removeActiveObject(): "
518                         <<"id="<<id<<" not found"<<std::endl;
519                 return;
520         }
521         obj->removeFromScene(true);
522         delete obj;
523         m_active_objects.erase(id);
524 }
525
526 void ClientEnvironment::processActiveObjectMessage(u16 id, const std::string &data)
527 {
528         ClientActiveObject *obj = getActiveObject(id);
529         if (obj == NULL) {
530                 infostream << "ClientEnvironment::processActiveObjectMessage():"
531                         << " got message for id=" << id << ", which doesn't exist."
532                         << std::endl;
533                 return;
534         }
535
536         try {
537                 obj->processMessage(data);
538         } catch (SerializationError &e) {
539                 errorstream<<"ClientEnvironment::processActiveObjectMessage():"
540                         << " id=" << id << " type=" << obj->getType()
541                         << " SerializationError in processMessage(): " << e.what()
542                         << std::endl;
543         }
544 }
545
546 /*
547         Callbacks for activeobjects
548 */
549
550 void ClientEnvironment::damageLocalPlayer(u8 damage, bool handle_hp)
551 {
552         LocalPlayer *lplayer = getLocalPlayer();
553         assert(lplayer);
554
555         if (handle_hp) {
556                 if (lplayer->hp > damage)
557                         lplayer->hp -= damage;
558                 else
559                         lplayer->hp = 0;
560         }
561
562         ClientEnvEvent event;
563         event.type = CEE_PLAYER_DAMAGE;
564         event.player_damage.amount = damage;
565         event.player_damage.send_to_server = handle_hp;
566         m_client_event_queue.push(event);
567 }
568
569 void ClientEnvironment::updateLocalPlayerBreath(u16 breath)
570 {
571         ClientEnvEvent event;
572         event.type = CEE_PLAYER_BREATH;
573         event.player_breath.amount = breath;
574         m_client_event_queue.push(event);
575 }
576
577 /*
578         Client likes to call these
579 */
580
581 void ClientEnvironment::getActiveObjects(v3f origin, f32 max_d,
582         std::vector<DistanceSortedActiveObject> &dest)
583 {
584         for (UNORDERED_MAP<u16, ClientActiveObject*>::iterator i = m_active_objects.begin();
585                 i != m_active_objects.end(); ++i) {
586                 ClientActiveObject* obj = i->second;
587
588                 f32 d = (obj->getPosition() - origin).getLength();
589
590                 if(d > max_d)
591                         continue;
592
593                 DistanceSortedActiveObject dso(obj, d);
594
595                 dest.push_back(dso);
596         }
597 }
598
599 ClientEnvEvent ClientEnvironment::getClientEvent()
600 {
601         ClientEnvEvent event;
602         if(m_client_event_queue.empty())
603                 event.type = CEE_NONE;
604         else {
605                 event = m_client_event_queue.front();
606                 m_client_event_queue.pop();
607         }
608         return event;
609 }
610
611 ClientActiveObject * ClientEnvironment::getSelectedActiveObject(
612         const core::line3d<f32> &shootline_on_map, v3f *intersection_point,
613         v3s16 *intersection_normal)
614 {
615         std::vector<DistanceSortedActiveObject> objects;
616         getActiveObjects(shootline_on_map.start,
617                 shootline_on_map.getLength() + 3, objects);
618         const v3f line_vector = shootline_on_map.getVector();
619
620         // Sort them.
621         // After this, the closest object is the first in the array.
622         std::sort(objects.begin(), objects.end());
623
624         /* Because objects can have different nodebox sizes,
625          * the object whose center is the nearest isn't necessarily
626          * the closest one. If an object is found, don't stop
627          * immediately. */
628
629         f32 d_min = shootline_on_map.getLength();
630         ClientActiveObject *nearest_obj = NULL;
631         for (u32 i = 0; i < objects.size(); i++) {
632                 ClientActiveObject *obj = objects[i].obj;
633
634                 aabb3f *selection_box = obj->getSelectionBox();
635                 if (selection_box == NULL)
636                         continue;
637
638                 v3f pos = obj->getPosition();
639
640                 aabb3f offsetted_box(selection_box->MinEdge + pos,
641                         selection_box->MaxEdge + pos);
642
643                 if (offsetted_box.getCenter().getDistanceFrom(
644                         shootline_on_map.start) > d_min + 9.6f*BS) {
645                         // Probably there is no active object that has bigger nodebox than
646                         // (-5.5,-5.5,-5.5,5.5,5.5,5.5)
647                         // 9.6 > 5.5*sqrt(3)
648                         break;
649                 }
650
651                 v3f current_intersection;
652                 v3s16 current_normal;
653                 if (boxLineCollision(offsetted_box, shootline_on_map.start, line_vector,
654                         &current_intersection, &current_normal)) {
655                         f32 d_current = current_intersection.getDistanceFrom(
656                                 shootline_on_map.start);
657                         if (d_current <= d_min) {
658                                 d_min = d_current;
659                                 nearest_obj = obj;
660                                 *intersection_point = current_intersection;
661                                 *intersection_normal = current_normal;
662                         }
663                 }
664         }
665
666         return nearest_obj;
667 }
668
669 /*
670         Check if a node is pointable
671 */
672 static inline bool isPointableNode(const MapNode &n,
673         INodeDefManager *ndef, bool liquids_pointable)
674 {
675         const ContentFeatures &features = ndef->get(n);
676         return features.pointable ||
677                 (liquids_pointable && features.isLiquid());
678 }
679
680 PointedThing ClientEnvironment::getPointedThing(
681         core::line3d<f32> shootline,
682         bool liquids_pointable,
683         bool look_for_object)
684 {
685         PointedThing result;
686
687         INodeDefManager *nodedef = m_map->getNodeDefManager();
688
689         core::aabbox3d<s16> maximal_exceed = nodedef->getSelectionBoxIntUnion();
690         // The code needs to search these nodes
691         core::aabbox3d<s16> search_range(-maximal_exceed.MaxEdge,
692                 -maximal_exceed.MinEdge);
693         // If a node is found, there might be a larger node behind.
694         // To find it, we have to go further.
695         s16 maximal_overcheck =
696                 std::max(abs(search_range.MinEdge.X), abs(search_range.MaxEdge.X))
697                         + std::max(abs(search_range.MinEdge.Y), abs(search_range.MaxEdge.Y))
698                         + std::max(abs(search_range.MinEdge.Z), abs(search_range.MaxEdge.Z));
699
700         const v3f original_vector = shootline.getVector();
701         const f32 original_length = original_vector.getLength();
702
703         f32 min_distance = original_length;
704
705         // First try to find an active object
706         if (look_for_object) {
707                 ClientActiveObject *selected_object = getSelectedActiveObject(
708                         shootline, &result.intersection_point,
709                         &result.intersection_normal);
710
711                 if (selected_object != NULL) {
712                         min_distance =
713                                 (result.intersection_point - shootline.start).getLength();
714
715                         result.type = POINTEDTHING_OBJECT;
716                         result.object_id = selected_object->getId();
717                 }
718         }
719
720         // Reduce shootline
721         if (original_length > 0) {
722                 shootline.end = shootline.start
723                         + shootline.getVector() / original_length * min_distance;
724         }
725
726         // Try to find a node that is closer than the selected active
727         // object (if it exists).
728
729         voxalgo::VoxelLineIterator iterator(shootline.start / BS,
730                 shootline.getVector() / BS);
731         v3s16 oldnode = iterator.m_current_node_pos;
732         // Indicates that a node was found.
733         bool is_node_found = false;
734         // If a node is found, it is possible that there's a node
735         // behind it with a large nodebox, so continue the search.
736         u16 node_foundcounter = 0;
737         // If a node is found, this is the center of the
738         // first nodebox the shootline meets.
739         v3f found_boxcenter(0, 0, 0);
740         // The untested nodes are in this range.
741         core::aabbox3d<s16> new_nodes;
742         while (true) {
743                 // Test the nodes around the current node in search_range.
744                 new_nodes = search_range;
745                 new_nodes.MinEdge += iterator.m_current_node_pos;
746                 new_nodes.MaxEdge += iterator.m_current_node_pos;
747
748                 // Only check new nodes
749                 v3s16 delta = iterator.m_current_node_pos - oldnode;
750                 if (delta.X > 0)
751                         new_nodes.MinEdge.X = new_nodes.MaxEdge.X;
752                 else if (delta.X < 0)
753                         new_nodes.MaxEdge.X = new_nodes.MinEdge.X;
754                 else if (delta.Y > 0)
755                         new_nodes.MinEdge.Y = new_nodes.MaxEdge.Y;
756                 else if (delta.Y < 0)
757                         new_nodes.MaxEdge.Y = new_nodes.MinEdge.Y;
758                 else if (delta.Z > 0)
759                         new_nodes.MinEdge.Z = new_nodes.MaxEdge.Z;
760                 else if (delta.Z < 0)
761                         new_nodes.MaxEdge.Z = new_nodes.MinEdge.Z;
762
763                 // For each untested node
764                 for (s16 x = new_nodes.MinEdge.X; x <= new_nodes.MaxEdge.X; x++) {
765                         for (s16 y = new_nodes.MinEdge.Y; y <= new_nodes.MaxEdge.Y; y++) {
766                                 for (s16 z = new_nodes.MinEdge.Z; z <= new_nodes.MaxEdge.Z; z++) {
767                                         MapNode n;
768                                         v3s16 np(x, y, z);
769                                         bool is_valid_position;
770
771                                         n = m_map->getNodeNoEx(np, &is_valid_position);
772                                         if (!(is_valid_position &&
773                                                 isPointableNode(n, nodedef, liquids_pointable))) {
774                                                 continue;
775                                         }
776                                         std::vector<aabb3f> boxes;
777                                         n.getSelectionBoxes(nodedef, &boxes,
778                                                 n.getNeighbors(np, m_map));
779
780                                         v3f npf = intToFloat(np, BS);
781                                         for (std::vector<aabb3f>::const_iterator i = boxes.begin();
782                                                 i != boxes.end(); ++i) {
783                                                 aabb3f box = *i;
784                                                 box.MinEdge += npf;
785                                                 box.MaxEdge += npf;
786                                                 v3f intersection_point;
787                                                 v3s16 intersection_normal;
788                                                 if (!boxLineCollision(box, shootline.start, shootline.getVector(),
789                                                         &intersection_point, &intersection_normal)) {
790                                                         continue;
791                                                 }
792                                                 f32 distance = (intersection_point - shootline.start).getLength();
793                                                 if (distance >= min_distance) {
794                                                         continue;
795                                                 }
796                                                 result.type = POINTEDTHING_NODE;
797                                                 result.node_undersurface = np;
798                                                 result.intersection_point = intersection_point;
799                                                 result.intersection_normal = intersection_normal;
800                                                 found_boxcenter = box.getCenter();
801                                                 min_distance = distance;
802                                                 is_node_found = true;
803                                         }
804                                 }
805                         }
806                 }
807                 if (is_node_found) {
808                         node_foundcounter++;
809                         if (node_foundcounter > maximal_overcheck) {
810                                 break;
811                         }
812                 }
813                 // Next node
814                 if (iterator.hasNext()) {
815                         oldnode = iterator.m_current_node_pos;
816                         iterator.next();
817                 } else {
818                         break;
819                 }
820         }
821
822         if (is_node_found) {
823                 // Set undersurface and abovesurface nodes
824                 f32 d = 0.002 * BS;
825                 v3f fake_intersection = result.intersection_point;
826                 // Move intersection towards its source block.
827                 if (fake_intersection.X < found_boxcenter.X)
828                         fake_intersection.X += d;
829                 else
830                         fake_intersection.X -= d;
831
832                 if (fake_intersection.Y < found_boxcenter.Y)
833                         fake_intersection.Y += d;
834                 else
835                         fake_intersection.Y -= d;
836
837                 if (fake_intersection.Z < found_boxcenter.Z)
838                         fake_intersection.Z += d;
839                 else
840                         fake_intersection.Z -= d;
841
842                 result.node_real_undersurface = floatToInt(fake_intersection, BS);
843                 result.node_abovesurface = result.node_real_undersurface
844                         + result.intersection_normal;
845         }
846         return result;
847 }