1 /*
2 Minetest
3 Copyright (C) 2010-2017 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "util/serialize.h"
21 #include "util/pointedthing.h"
22 #include "client.h"
23 #include "clientenvironment.h"
24 #include "clientsimpleobject.h"
25 #include "clientmap.h"
26 #include "scripting_client.h"
27 #include "mapblock_mesh.h"
28 #include "mtevent.h"
29 #include "collision.h"
30 #include "nodedef.h"
31 #include "profiler.h"
32 #include "raycast.h"
33 #include "voxelalgorithms.h"
34 #include "settings.h"
35 #include "shader.h"
36 #include "content_cao.h"
37 #include <algorithm>
38 #include "client/renderingengine.h"
39
40 /*
41 CAOShaderConstantSetter
42 */
43
44 //! Shader constant setter for passing material emissive color to the CAO object_shader
45 class CAOShaderConstantSetter : public IShaderConstantSetter
46 {
47 public:
CAOShaderConstantSetter()48 CAOShaderConstantSetter():
49 m_emissive_color_setting("emissiveColor")
50 {}
51
52 ~CAOShaderConstantSetter() override = default;
53
onSetConstants(video::IMaterialRendererServices * services)54 void onSetConstants(video::IMaterialRendererServices *services) override
55 {
56 // Ambient color
57 video::SColorf emissive_color(m_emissive_color);
58
59 float as_array[4] = {
60 emissive_color.r,
61 emissive_color.g,
62 emissive_color.b,
63 emissive_color.a,
64 };
65 m_emissive_color_setting.set(as_array, services);
66 }
67
onSetMaterial(const video::SMaterial & material)68 void onSetMaterial(const video::SMaterial& material) override
69 {
70 m_emissive_color = material.EmissiveColor;
71 }
72
73 private:
74 video::SColor m_emissive_color;
75 CachedPixelShaderSetting<float, 4> m_emissive_color_setting;
76 };
77
78 class CAOShaderConstantSetterFactory : public IShaderConstantSetterFactory
79 {
80 public:
CAOShaderConstantSetterFactory()81 CAOShaderConstantSetterFactory()
82 {}
83
create()84 virtual IShaderConstantSetter* create()
85 {
86 return new CAOShaderConstantSetter();
87 }
88 };
89
90 /*
91 ClientEnvironment
92 */
93
ClientEnvironment(ClientMap * map,ITextureSource * texturesource,Client * client)94 ClientEnvironment::ClientEnvironment(ClientMap *map,
95 ITextureSource *texturesource, Client *client):
96 Environment(client),
97 m_map(map),
98 m_texturesource(texturesource),
99 m_client(client)
100 {
101 auto *shdrsrc = m_client->getShaderSource();
102 shdrsrc->addShaderConstantSetterFactory(new CAOShaderConstantSetterFactory());
103 }
104
~ClientEnvironment()105 ClientEnvironment::~ClientEnvironment()
106 {
107 m_ao_manager.clear();
108
109 for (auto &simple_object : m_simple_objects) {
110 delete simple_object;
111 }
112
113 // Drop/delete map
114 m_map->drop();
115
116 delete m_local_player;
117 }
118
getMap()119 Map & ClientEnvironment::getMap()
120 {
121 return *m_map;
122 }
123
getClientMap()124 ClientMap & ClientEnvironment::getClientMap()
125 {
126 return *m_map;
127 }
128
setLocalPlayer(LocalPlayer * player)129 void ClientEnvironment::setLocalPlayer(LocalPlayer *player)
130 {
131 /*
132 It is a failure if already is a local player
133 */
134 FATAL_ERROR_IF(m_local_player != NULL,
135 "Local player already allocated");
136
137 m_local_player = player;
138 }
139
step(float dtime)140 void ClientEnvironment::step(float dtime)
141 {
142 /* Step time of day */
143 stepTimeOfDay(dtime);
144
145 // Get some settings
146 bool fly_allowed = m_client->checkLocalPrivilege("fly");
147 bool free_move = fly_allowed && g_settings->getBool("free_move");
148
149 // Get local player
150 LocalPlayer *lplayer = getLocalPlayer();
151 assert(lplayer);
152 // collision info queue
153 std::vector<CollisionInfo> player_collisions;
154
155 /*
156 Get the speed the player is going
157 */
158 bool is_climbing = lplayer->is_climbing;
159
160 f32 player_speed = lplayer->getSpeed().getLength();
161
162 /*
163 Maximum position increment
164 */
165 //f32 position_max_increment = 0.05*BS;
166 f32 position_max_increment = 0.1*BS;
167
168 // Maximum time increment (for collision detection etc)
169 // time = distance / speed
170 f32 dtime_max_increment = 1;
171 if(player_speed > 0.001)
172 dtime_max_increment = position_max_increment / player_speed;
173
174 // Maximum time increment is 10ms or lower
175 if(dtime_max_increment > 0.01)
176 dtime_max_increment = 0.01;
177
178 // Don't allow overly huge dtime
179 if(dtime > 0.5)
180 dtime = 0.5;
181
182 /*
183 Stuff that has a maximum time increment
184 */
185
186 u32 steps = ceil(dtime / dtime_max_increment);
187 f32 dtime_part = dtime / steps;
188 for (; steps > 0; --steps) {
189 /*
190 Local player handling
191 */
192
193 // Control local player
194 lplayer->applyControl(dtime_part, this);
195
196 // Apply physics
197 if (!free_move && !is_climbing) {
198 // Gravity
199 v3f speed = lplayer->getSpeed();
200 if (!lplayer->in_liquid)
201 speed.Y -= lplayer->movement_gravity *
202 lplayer->physics_override_gravity * dtime_part * 2.0f;
203
204 // Liquid floating / sinking
205 if (lplayer->in_liquid && !lplayer->swimming_vertical &&
206 !lplayer->swimming_pitch)
207 speed.Y -= lplayer->movement_liquid_sink * dtime_part * 2.0f;
208
209 // Liquid resistance
210 if (lplayer->in_liquid_stable || lplayer->in_liquid) {
211 // How much the node's viscosity blocks movement, ranges
212 // between 0 and 1. Should match the scale at which viscosity
213 // increase affects other liquid attributes.
214 static const f32 viscosity_factor = 0.3f;
215
216 v3f d_wanted = -speed / lplayer->movement_liquid_fluidity;
217 f32 dl = d_wanted.getLength();
218 if (dl > lplayer->movement_liquid_fluidity_smooth)
219 dl = lplayer->movement_liquid_fluidity_smooth;
220
221 dl *= (lplayer->liquid_viscosity * viscosity_factor) +
222 (1 - viscosity_factor);
223 v3f d = d_wanted.normalize() * (dl * dtime_part * 100.0f);
224 speed += d;
225 }
226
227 lplayer->setSpeed(speed);
228 }
229
230 /*
231 Move the lplayer.
232 This also does collision detection.
233 */
234 lplayer->move(dtime_part, this, position_max_increment,
235 &player_collisions);
236 }
237
238 bool player_immortal = lplayer->getCAO() && lplayer->getCAO()->isImmortal();
239
240 for (const CollisionInfo &info : player_collisions) {
241 v3f speed_diff = info.new_speed - info.old_speed;;
242 // Handle only fall damage
243 // (because otherwise walking against something in fast_move kills you)
244 if (speed_diff.Y < 0 || info.old_speed.Y >= 0)
245 continue;
246 // Get rid of other components
247 speed_diff.X = 0;
248 speed_diff.Z = 0;
249 f32 pre_factor = 1; // 1 hp per node/s
250 f32 tolerance = BS*14; // 5 without damage
251 f32 post_factor = 1; // 1 hp per node/s
252 if (info.type == COLLISION_NODE) {
253 const ContentFeatures &f = m_client->ndef()->
254 get(m_map->getNode(info.node_p));
255 // Determine fall damage multiplier
256 int addp = itemgroup_get(f.groups, "fall_damage_add_percent");
257 pre_factor = 1.0f + (float)addp / 100.0f;
258 }
259 float speed = pre_factor * speed_diff.getLength();
260 if (speed > tolerance && !player_immortal) {
261 f32 damage_f = (speed - tolerance) / BS * post_factor;
262 u16 damage = (u16)MYMIN(damage_f + 0.5, U16_MAX);
263 if (damage != 0) {
264 damageLocalPlayer(damage, true);
265 m_client->getEventManager()->put(
266 new SimpleTriggerEvent(MtEvent::PLAYER_FALLING_DAMAGE));
267 }
268 }
269 }
270
271 if (m_client->modsLoaded())
272 m_script->environment_step(dtime);
273
274 // Update lighting on local player (used for wield item)
275 u32 day_night_ratio = getDayNightRatio();
276 {
277 // Get node at head
278
279 // On InvalidPositionException, use this as default
280 // (day: LIGHT_SUN, night: 0)
281 MapNode node_at_lplayer(CONTENT_AIR, 0x0f, 0);
282
283 v3s16 p = lplayer->getLightPosition();
284 node_at_lplayer = m_map->getNode(p);
285
286 u16 light = getInteriorLight(node_at_lplayer, 0, m_client->ndef());
287 final_color_blend(&lplayer->light_color, light, day_night_ratio);
288 }
289
290 /*
291 Step active objects and update lighting of them
292 */
293
294 bool update_lighting = m_active_object_light_update_interval.step(dtime, 0.21);
295 auto cb_state = [this, dtime, update_lighting, day_night_ratio] (ClientActiveObject *cao) {
296 // Step object
297 cao->step(dtime, this);
298
299 if (update_lighting)
300 cao->updateLight(day_night_ratio);
301 };
302
303 m_ao_manager.step(dtime, cb_state);
304
305 /*
306 Step and handle simple objects
307 */
308 g_profiler->avg("ClientEnv: CSO count [#]", m_simple_objects.size());
309 for (auto i = m_simple_objects.begin(); i != m_simple_objects.end();) {
310 ClientSimpleObject *simple = *i;
311
312 simple->step(dtime);
313 if(simple->m_to_be_removed) {
314 delete simple;
315 i = m_simple_objects.erase(i);
316 }
317 else {
318 ++i;
319 }
320 }
321 }
322
addSimpleObject(ClientSimpleObject * simple)323 void ClientEnvironment::addSimpleObject(ClientSimpleObject *simple)
324 {
325 m_simple_objects.push_back(simple);
326 }
327
getGenericCAO(u16 id)328 GenericCAO* ClientEnvironment::getGenericCAO(u16 id)
329 {
330 ClientActiveObject *obj = getActiveObject(id);
331 if (obj && obj->getType() == ACTIVEOBJECT_TYPE_GENERIC)
332 return (GenericCAO*) obj;
333
334 return NULL;
335 }
336
addActiveObject(ClientActiveObject * object)337 u16 ClientEnvironment::addActiveObject(ClientActiveObject *object)
338 {
339 // Register object. If failed return zero id
340 if (!m_ao_manager.registerObject(object))
341 return 0;
342
343 object->addToScene(m_texturesource);
344
345 // Update lighting immediately
346 object->updateLight(getDayNightRatio());
347 return object->getId();
348 }
349
addActiveObject(u16 id,u8 type,const std::string & init_data)350 void ClientEnvironment::addActiveObject(u16 id, u8 type,
351 const std::string &init_data)
352 {
353 ClientActiveObject* obj =
354 ClientActiveObject::create((ActiveObjectType) type, m_client, this);
355 if(obj == NULL)
356 {
357 infostream<<"ClientEnvironment::addActiveObject(): "
358 <<"id="<<id<<" type="<<type<<": Couldn't create object"
359 <<std::endl;
360 return;
361 }
362
363 obj->setId(id);
364
365 try
366 {
367 obj->initialize(init_data);
368 }
369 catch(SerializationError &e)
370 {
371 errorstream<<"ClientEnvironment::addActiveObject():"
372 <<" id="<<id<<" type="<<type
373 <<": SerializationError in initialize(): "
374 <<e.what()
375 <<": init_data="<<serializeJsonString(init_data)
376 <<std::endl;
377 }
378
379 u16 new_id = addActiveObject(obj);
380 // Object initialized:
381 if ((obj = getActiveObject(new_id))) {
382 // Final step is to update all children which are already known
383 // Data provided by AO_CMD_SPAWN_INFANT
384 const auto &children = obj->getAttachmentChildIds();
385 for (auto c_id : children) {
386 if (auto *o = getActiveObject(c_id))
387 o->updateAttachments();
388 }
389 }
390 }
391
392
removeActiveObject(u16 id)393 void ClientEnvironment::removeActiveObject(u16 id)
394 {
395 // Get current attachment childs to detach them visually
396 std::unordered_set<int> attachment_childs;
397 if (auto *obj = getActiveObject(id))
398 attachment_childs = obj->getAttachmentChildIds();
399
400 m_ao_manager.removeObject(id);
401
402 // Perform a proper detach in Irrlicht
403 for (auto c_id : attachment_childs) {
404 if (ClientActiveObject *child = getActiveObject(c_id))
405 child->updateAttachments();
406 }
407 }
408
processActiveObjectMessage(u16 id,const std::string & data)409 void ClientEnvironment::processActiveObjectMessage(u16 id, const std::string &data)
410 {
411 ClientActiveObject *obj = getActiveObject(id);
412 if (obj == NULL) {
413 infostream << "ClientEnvironment::processActiveObjectMessage():"
414 << " got message for id=" << id << ", which doesn't exist."
415 << std::endl;
416 return;
417 }
418
419 try {
420 obj->processMessage(data);
421 } catch (SerializationError &e) {
422 errorstream<<"ClientEnvironment::processActiveObjectMessage():"
423 << " id=" << id << " type=" << obj->getType()
424 << " SerializationError in processMessage(): " << e.what()
425 << std::endl;
426 }
427 }
428
429 /*
430 Callbacks for activeobjects
431 */
432
damageLocalPlayer(u16 damage,bool handle_hp)433 void ClientEnvironment::damageLocalPlayer(u16 damage, bool handle_hp)
434 {
435 LocalPlayer *lplayer = getLocalPlayer();
436 assert(lplayer);
437
438 if (handle_hp) {
439 if (lplayer->hp > damage)
440 lplayer->hp -= damage;
441 else
442 lplayer->hp = 0;
443 }
444
445 ClientEnvEvent event;
446 event.type = CEE_PLAYER_DAMAGE;
447 event.player_damage.amount = damage;
448 event.player_damage.send_to_server = handle_hp;
449 m_client_event_queue.push(event);
450 }
451
452 /*
453 Client likes to call these
454 */
455
getClientEnvEvent()456 ClientEnvEvent ClientEnvironment::getClientEnvEvent()
457 {
458 FATAL_ERROR_IF(m_client_event_queue.empty(),
459 "ClientEnvironment::getClientEnvEvent(): queue is empty");
460
461 ClientEnvEvent event = m_client_event_queue.front();
462 m_client_event_queue.pop();
463 return event;
464 }
465
getSelectedActiveObjects(const core::line3d<f32> & shootline_on_map,std::vector<PointedThing> & objects)466 void ClientEnvironment::getSelectedActiveObjects(
467 const core::line3d<f32> &shootline_on_map,
468 std::vector<PointedThing> &objects)
469 {
470 std::vector<DistanceSortedActiveObject> allObjects;
471 getActiveObjects(shootline_on_map.start,
472 shootline_on_map.getLength() + 10.0f, allObjects);
473 const v3f line_vector = shootline_on_map.getVector();
474
475 for (const auto &allObject : allObjects) {
476 ClientActiveObject *obj = allObject.obj;
477 aabb3f selection_box;
478 if (!obj->getSelectionBox(&selection_box))
479 continue;
480
481 const v3f &pos = obj->getPosition();
482 aabb3f offsetted_box(selection_box.MinEdge + pos,
483 selection_box.MaxEdge + pos);
484
485 v3f current_intersection;
486 v3s16 current_normal;
487 if (boxLineCollision(offsetted_box, shootline_on_map.start, line_vector,
488 ¤t_intersection, ¤t_normal)) {
489 objects.emplace_back((s16) obj->getId(), current_intersection, current_normal,
490 (current_intersection - shootline_on_map.start).getLengthSQ());
491 }
492 }
493 }
494