3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
20 #include "content_cao.h"
21 #include <IBillboardSceneNode.h>
22 #include <ICameraSceneNode.h>
23 #include <ITextSceneNode.h>
24 #include <IMeshManipulator.h>
25 #include <IAnimatedMeshSceneNode.h>
26 #include "client/client.h"
27 #include "client/renderingengine.h"
28 #include "client/sound.h"
29 #include "client/tile.h"
30 #include "util/basic_macros.h"
31 #include "util/numeric.h" // For IntervalLimiter & setPitchYawRoll
32 #include "util/serialize.h"
33 #include "camera.h" // CameraModes
34 #include "collision.h"
35 #include "content_cso.h"
36 #include "environment.h"
38 #include "localplayer.h"
42 #include "serialization.h" // For decompressZlib
46 #include "wieldmesh.h"
49 #include "client/shader.h"
50 #include "script/scripting_client.h"
51 #include "client/minimap.h"
54 struct ToolCapabilities;
56 std::unordered_map<u16, ClientActiveObject::Factory> ClientActiveObject::m_types;
59 void SmoothTranslator<T>::init(T current)
62 val_current = current;
65 anim_time_counter = 0;
70 void SmoothTranslator<T>::update(T new_target, bool is_end_position, float update_interval)
72 aim_is_end = is_end_position;
73 val_old = val_current;
74 val_target = new_target;
75 if (update_interval > 0) {
76 anim_time = update_interval;
78 if (anim_time < 0.001 || anim_time > 1.0)
79 anim_time = anim_time_counter;
81 anim_time = anim_time * 0.9 + anim_time_counter * 0.1;
83 anim_time_counter = 0;
87 void SmoothTranslator<T>::translate(f32 dtime)
89 anim_time_counter = anim_time_counter + dtime;
90 T val_diff = val_target - val_old;
92 if (anim_time > 0.001)
93 moveratio = anim_time_counter / anim_time;
94 f32 move_end = aim_is_end ? 1.0 : 1.5;
96 // Move a bit less than should, to avoid oscillation
97 moveratio = std::min(moveratio * 0.8f, move_end);
98 val_current = val_old + val_diff * moveratio;
101 void SmoothTranslatorWrapped::translate(f32 dtime)
103 anim_time_counter = anim_time_counter + dtime;
104 f32 val_diff = std::abs(val_target - val_old);
105 if (val_diff > 180.f)
106 val_diff = 360.f - val_diff;
109 if (anim_time > 0.001)
110 moveratio = anim_time_counter / anim_time;
111 f32 move_end = aim_is_end ? 1.0 : 1.5;
113 // Move a bit less than should, to avoid oscillation
114 moveratio = std::min(moveratio * 0.8f, move_end);
115 wrappedApproachShortest(val_current, val_target,
116 val_diff * moveratio, 360.f);
119 void SmoothTranslatorWrappedv3f::translate(f32 dtime)
121 anim_time_counter = anim_time_counter + dtime;
124 val_diff_v3f.X = std::abs(val_target.X - val_old.X);
125 val_diff_v3f.Y = std::abs(val_target.Y - val_old.Y);
126 val_diff_v3f.Z = std::abs(val_target.Z - val_old.Z);
128 if (val_diff_v3f.X > 180.f)
129 val_diff_v3f.X = 360.f - val_diff_v3f.X;
131 if (val_diff_v3f.Y > 180.f)
132 val_diff_v3f.Y = 360.f - val_diff_v3f.Y;
134 if (val_diff_v3f.Z > 180.f)
135 val_diff_v3f.Z = 360.f - val_diff_v3f.Z;
138 if (anim_time > 0.001)
139 moveratio = anim_time_counter / anim_time;
140 f32 move_end = aim_is_end ? 1.0 : 1.5;
142 // Move a bit less than should, to avoid oscillation
143 moveratio = std::min(moveratio * 0.8f, move_end);
144 wrappedApproachShortest(val_current.X, val_target.X,
145 val_diff_v3f.X * moveratio, 360.f);
147 wrappedApproachShortest(val_current.Y, val_target.Y,
148 val_diff_v3f.Y * moveratio, 360.f);
150 wrappedApproachShortest(val_current.Z, val_target.Z,
151 val_diff_v3f.Z * moveratio, 360.f);
158 static void setBillboardTextureMatrix(scene::IBillboardSceneNode *bill,
159 float txs, float tys, int col, int row)
161 video::SMaterial& material = bill->getMaterial(0);
162 core::matrix4& matrix = material.getTextureMatrix(0);
163 matrix.setTextureTranslate(txs*col, tys*row);
164 matrix.setTextureScale(txs, tys);
167 // Evaluate transform chain recursively; irrlicht does not do this for us
168 static void updatePositionRecursive(scene::ISceneNode *node)
170 scene::ISceneNode *parent = node->getParent();
172 updatePositionRecursive(parent);
173 node->updateAbsolutePosition();
180 class TestCAO : public ClientActiveObject
183 TestCAO(Client *client, ClientEnvironment *env);
184 virtual ~TestCAO() = default;
186 ActiveObjectType getType() const
188 return ACTIVEOBJECT_TYPE_TEST;
191 static ClientActiveObject* create(Client *client, ClientEnvironment *env);
193 void addToScene(ITextureSource *tsrc);
194 void removeFromScene(bool permanent);
195 void updateLight(u32 day_night_ratio);
196 void updateNodePos();
198 void step(float dtime, ClientEnvironment *env);
200 void processMessage(const std::string &data);
202 bool getCollisionBox(aabb3f *toset) const { return false; }
204 scene::IMeshSceneNode *m_node;
209 TestCAO proto_TestCAO(NULL, NULL);
211 TestCAO::TestCAO(Client *client, ClientEnvironment *env):
212 ClientActiveObject(0, client, env),
214 m_position(v3f(0,10*BS,0))
216 ClientActiveObject::registerType(getType(), create);
219 ClientActiveObject* TestCAO::create(Client *client, ClientEnvironment *env)
221 return new TestCAO(client, env);
224 void TestCAO::addToScene(ITextureSource *tsrc)
229 //video::IVideoDriver* driver = smgr->getVideoDriver();
231 scene::SMesh *mesh = new scene::SMesh();
232 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
233 video::SColor c(255,255,255,255);
234 video::S3DVertex vertices[4] =
236 video::S3DVertex(-BS/2,-BS/4,0, 0,0,0, c, 0,1),
237 video::S3DVertex(BS/2,-BS/4,0, 0,0,0, c, 1,1),
238 video::S3DVertex(BS/2,BS/4,0, 0,0,0, c, 1,0),
239 video::S3DVertex(-BS/2,BS/4,0, 0,0,0, c, 0,0),
241 u16 indices[] = {0,1,2,2,3,0};
242 buf->append(vertices, 4, indices, 6);
244 buf->getMaterial().setFlag(video::EMF_LIGHTING, true); // false
245 buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
246 buf->getMaterial().setTexture(0, tsrc->getTextureForMesh("rat.png"));
247 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
248 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
249 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
251 mesh->addMeshBuffer(buf);
253 m_node = RenderingEngine::get_scene_manager()->addMeshSceneNode(mesh, NULL);
258 void TestCAO::removeFromScene(bool permanent)
267 void TestCAO::updateLight(u32 day_night_ratio)
271 void TestCAO::updateNodePos()
276 m_node->setPosition(m_position);
277 //m_node->setRotation(v3f(0, 45, 0));
280 void TestCAO::step(float dtime, ClientEnvironment *env)
284 v3f rot = m_node->getRotation();
285 //infostream<<"dtime="<<dtime<<", rot.Y="<<rot.Y<<std::endl;
286 rot.Y += dtime * 180;
287 m_node->setRotation(rot);
291 void TestCAO::processMessage(const std::string &data)
293 infostream<<"TestCAO: Got data: "<<data<<std::endl;
294 std::istringstream is(data, std::ios::binary);
312 #include "clientobject.h"
314 GenericCAO::GenericCAO(Client *client, ClientEnvironment *env):
315 ClientActiveObject(0, client, env)
317 if (client == NULL) {
318 ClientActiveObject::registerType(getType(), create);
324 bool GenericCAO::getCollisionBox(aabb3f *toset) const
328 //update collision box
329 toset->MinEdge = m_prop.collisionbox.MinEdge * BS;
330 toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS;
332 toset->MinEdge += m_position;
333 toset->MaxEdge += m_position;
341 bool GenericCAO::collideWithObjects() const
343 return m_prop.collideWithObjects;
346 void GenericCAO::initialize(const std::string &data)
348 infostream<<"GenericCAO: Got init data"<<std::endl;
349 processInitData(data);
352 // Check if it's the current player
353 LocalPlayer *player = m_env->getLocalPlayer();
354 if (player && strcmp(player->getName(), m_name.c_str()) == 0) {
355 m_is_local_player = true;
356 m_is_visible = false;
357 player->setCAO(this);
359 m_prop.show_on_minimap = false;
363 m_enable_shaders = g_settings->getBool("enable_shaders");
366 void GenericCAO::processInitData(const std::string &data)
368 std::istringstream is(data, std::ios::binary);
369 const u8 version = readU8(is);
372 errorstream << "GenericCAO: Unsupported init data version"
377 // PROTOCOL_VERSION >= 37
378 m_name = deSerializeString16(is);
379 m_is_player = readU8(is);
381 m_position = readV3F32(is);
382 m_rotation = readV3F32(is);
385 const u8 num_messages = readU8(is);
387 for (int i = 0; i < num_messages; i++) {
388 std::string message = deSerializeString32(is);
389 processMessage(message);
392 m_rotation = wrapDegrees_0_360_v3f(m_rotation);
393 pos_translator.init(m_position);
394 rot_translator.init(m_rotation);
398 GenericCAO::~GenericCAO()
400 removeFromScene(true);
403 bool GenericCAO::getSelectionBox(aabb3f *toset) const
405 if (!m_prop.is_visible || !m_is_visible || m_is_local_player
406 || !m_prop.pointable) {
409 *toset = m_selection_box;
413 const v3f GenericCAO::getPosition() const
416 return pos_translator.val_current;
418 // Calculate real position in world based on MatrixNode
420 v3s16 camera_offset = m_env->getCameraOffset();
421 return m_matrixnode->getAbsolutePosition() +
422 intToFloat(camera_offset, BS);
428 const bool GenericCAO::isImmortal()
430 return itemgroup_get(getGroups(), "immortal");
433 scene::ISceneNode *GenericCAO::getSceneNode() const
439 if (m_animated_meshnode) {
440 return m_animated_meshnode;
443 if (m_wield_meshnode) {
444 return m_wield_meshnode;
453 scene::IAnimatedMeshSceneNode *GenericCAO::getAnimatedMeshSceneNode() const
455 return m_animated_meshnode;
458 void GenericCAO::setChildrenVisible(bool toset)
460 for (u16 cao_id : m_attachment_child_ids) {
461 GenericCAO *obj = m_env->getGenericCAO(cao_id);
463 // Check if the entity is forced to appear in first person.
464 obj->setVisible(obj->m_force_visible ? true : toset);
469 void GenericCAO::setAttachment(int parent_id, const std::string &bone,
470 v3f position, v3f rotation, bool force_visible)
472 int old_parent = m_attachment_parent_id;
473 m_attachment_parent_id = parent_id;
474 m_attachment_bone = bone;
475 m_attachment_position = position;
476 m_attachment_rotation = rotation;
477 m_force_visible = force_visible;
479 ClientActiveObject *parent = m_env->getActiveObject(parent_id);
481 if (parent_id != old_parent) {
483 m_waiting_for_reattach = 10;
484 if (auto *o = m_env->getActiveObject(old_parent))
485 o->removeAttachmentChild(m_id);
487 parent->addAttachmentChild(m_id);
492 // Forcibly show attachments if required by set_attach
493 if (m_force_visible) {
495 } else if (!m_is_local_player) {
496 // Objects attached to the local player should be hidden in first person
497 m_is_visible = !m_attached_to_local ||
498 m_client->getCamera()->getCameraMode() != CAMERA_MODE_FIRST;
499 m_force_visible = false;
501 // Local players need to have this set,
502 // otherwise first person attachments fail.
507 void GenericCAO::getAttachment(int *parent_id, std::string *bone, v3f *position,
508 v3f *rotation, bool *force_visible) const
510 *parent_id = m_attachment_parent_id;
511 *bone = m_attachment_bone;
512 *position = m_attachment_position;
513 *rotation = m_attachment_rotation;
514 *force_visible = m_force_visible;
517 void GenericCAO::clearChildAttachments()
519 // Cannot use for-loop here: setAttachment() modifies 'm_attachment_child_ids'!
520 while (!m_attachment_child_ids.empty()) {
521 int child_id = *m_attachment_child_ids.begin();
523 if (ClientActiveObject *child = m_env->getActiveObject(child_id))
524 child->setAttachment(0, "", v3f(), v3f(), false);
526 removeAttachmentChild(child_id);
530 void GenericCAO::clearParentAttachment()
532 if (m_attachment_parent_id)
533 setAttachment(0, "", m_attachment_position, m_attachment_rotation, false);
535 setAttachment(0, "", v3f(), v3f(), false);
538 void GenericCAO::addAttachmentChild(int child_id)
540 m_attachment_child_ids.insert(child_id);
543 void GenericCAO::removeAttachmentChild(int child_id)
545 m_attachment_child_ids.erase(child_id);
548 ClientActiveObject* GenericCAO::getParent() const
550 return m_attachment_parent_id ? m_env->getActiveObject(m_attachment_parent_id) :
554 void GenericCAO::removeFromScene(bool permanent)
556 // Should be true when removing the object permanently
557 // and false when refreshing (eg: updating visuals)
558 if (m_env && permanent) {
559 // The client does not know whether this object does re-appear to
560 // a later time, thus do not clear child attachments.
562 clearParentAttachment();
566 m_meshnode->remove();
568 m_meshnode = nullptr;
569 } else if (m_animated_meshnode) {
570 m_animated_meshnode->remove();
571 m_animated_meshnode->drop();
572 m_animated_meshnode = nullptr;
573 } else if (m_wield_meshnode) {
574 m_wield_meshnode->remove();
575 m_wield_meshnode->drop();
576 m_wield_meshnode = nullptr;
577 } else if (m_spritenode) {
578 m_spritenode->remove();
579 m_spritenode->drop();
580 m_spritenode = nullptr;
584 m_matrixnode->remove();
585 m_matrixnode->drop();
586 m_matrixnode = nullptr;
590 m_client->getCamera()->removeNametag(m_nametag);
594 if (m_marker && m_client->getMinimap())
595 m_client->getMinimap()->removeMarker(&m_marker);
598 void GenericCAO::addToScene(ITextureSource *tsrc)
600 m_smgr = RenderingEngine::get_scene_manager();
602 if (getSceneNode() != NULL) {
606 m_visuals_expired = false;
608 if (!m_prop.is_visible)
611 infostream << "GenericCAO::addToScene(): " << m_prop.visual << std::endl;
613 if (m_enable_shaders) {
614 IShaderSource *shader_source = m_client->getShaderSource();
615 MaterialType material_type;
617 if (m_prop.shaded && m_prop.glow == 0)
618 material_type = (m_prop.use_texture_alpha) ?
619 TILE_MATERIAL_ALPHA : TILE_MATERIAL_BASIC;
621 material_type = (m_prop.use_texture_alpha) ?
622 TILE_MATERIAL_PLAIN_ALPHA : TILE_MATERIAL_PLAIN;
624 u32 shader_id = shader_source->getShader("object_shader", material_type, NDT_NORMAL);
625 m_material_type = shader_source->getShaderInfo(shader_id).material;
627 m_material_type = (m_prop.use_texture_alpha) ?
628 video::EMT_TRANSPARENT_ALPHA_CHANNEL : video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
631 auto grabMatrixNode = [this] {
632 m_matrixnode = RenderingEngine::get_scene_manager()->
633 addDummyTransformationSceneNode();
634 m_matrixnode->grab();
637 auto setSceneNodeMaterial = [this] (scene::ISceneNode *node) {
638 node->setMaterialFlag(video::EMF_LIGHTING, false);
639 node->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
640 node->setMaterialFlag(video::EMF_FOG_ENABLE, true);
641 node->setMaterialType(m_material_type);
643 if (m_enable_shaders) {
644 node->setMaterialFlag(video::EMF_GOURAUD_SHADING, false);
645 node->setMaterialFlag(video::EMF_NORMALIZE_NORMALS, true);
649 if (m_prop.visual == "sprite") {
651 m_spritenode = RenderingEngine::get_scene_manager()->addBillboardSceneNode(
652 m_matrixnode, v2f(1, 1), v3f(0,0,0), -1);
653 m_spritenode->grab();
654 m_spritenode->setMaterialTexture(0,
655 tsrc->getTextureForMesh("unknown_node.png"));
657 setSceneNodeMaterial(m_spritenode);
659 m_spritenode->setSize(v2f(m_prop.visual_size.X,
660 m_prop.visual_size.Y) * BS);
662 const float txs = 1.0 / 1;
663 const float tys = 1.0 / 1;
664 setBillboardTextureMatrix(m_spritenode,
667 } else if (m_prop.visual == "upright_sprite") {
669 scene::SMesh *mesh = new scene::SMesh();
670 double dx = BS * m_prop.visual_size.X / 2;
671 double dy = BS * m_prop.visual_size.Y / 2;
672 video::SColor c(0xFFFFFFFF);
675 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
676 video::S3DVertex vertices[4] = {
677 video::S3DVertex(-dx, -dy, 0, 0,0,1, c, 1,1),
678 video::S3DVertex( dx, -dy, 0, 0,0,1, c, 0,1),
679 video::S3DVertex( dx, dy, 0, 0,0,1, c, 0,0),
680 video::S3DVertex(-dx, dy, 0, 0,0,1, c, 1,0),
683 // Move minimal Y position to 0 (feet position)
684 for (video::S3DVertex &vertex : vertices)
687 u16 indices[] = {0,1,2,2,3,0};
688 buf->append(vertices, 4, indices, 6);
690 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
691 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
692 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
693 buf->getMaterial().MaterialType = m_material_type;
695 if (m_enable_shaders) {
696 buf->getMaterial().EmissiveColor = c;
697 buf->getMaterial().setFlag(video::EMF_GOURAUD_SHADING, false);
698 buf->getMaterial().setFlag(video::EMF_NORMALIZE_NORMALS, true);
702 mesh->addMeshBuffer(buf);
706 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
707 video::S3DVertex vertices[4] = {
708 video::S3DVertex( dx,-dy, 0, 0,0,-1, c, 1,1),
709 video::S3DVertex(-dx,-dy, 0, 0,0,-1, c, 0,1),
710 video::S3DVertex(-dx, dy, 0, 0,0,-1, c, 0,0),
711 video::S3DVertex( dx, dy, 0, 0,0,-1, c, 1,0),
714 // Move minimal Y position to 0 (feet position)
715 for (video::S3DVertex &vertex : vertices)
718 u16 indices[] = {0,1,2,2,3,0};
719 buf->append(vertices, 4, indices, 6);
721 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
722 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
723 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
724 buf->getMaterial().MaterialType = m_material_type;
726 if (m_enable_shaders) {
727 buf->getMaterial().EmissiveColor = c;
728 buf->getMaterial().setFlag(video::EMF_GOURAUD_SHADING, false);
729 buf->getMaterial().setFlag(video::EMF_NORMALIZE_NORMALS, true);
733 mesh->addMeshBuffer(buf);
736 m_meshnode = RenderingEngine::get_scene_manager()->
737 addMeshSceneNode(mesh, m_matrixnode);
740 // Set it to use the materials of the meshbuffers directly.
741 // This is needed for changing the texture in the future
742 m_meshnode->setReadOnlyMaterials(true);
743 } else if (m_prop.visual == "cube") {
745 scene::IMesh *mesh = createCubeMesh(v3f(BS,BS,BS));
746 m_meshnode = RenderingEngine::get_scene_manager()->
747 addMeshSceneNode(mesh, m_matrixnode);
751 m_meshnode->setScale(m_prop.visual_size);
752 m_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
753 m_prop.backface_culling);
755 setSceneNodeMaterial(m_meshnode);
756 } else if (m_prop.visual == "mesh") {
758 scene::IAnimatedMesh *mesh = m_client->getMesh(m_prop.mesh, true);
760 m_animated_meshnode = RenderingEngine::get_scene_manager()->
761 addAnimatedMeshSceneNode(mesh, m_matrixnode);
762 m_animated_meshnode->grab();
763 mesh->drop(); // The scene node took hold of it
765 if (!checkMeshNormals(mesh)) {
766 infostream << "GenericCAO: recalculating normals for mesh "
767 << m_prop.mesh << std::endl;
768 m_smgr->getMeshManipulator()->
769 recalculateNormals(mesh, true, false);
772 m_animated_meshnode->animateJoints(); // Needed for some animations
773 m_animated_meshnode->setScale(m_prop.visual_size);
775 // set vertex colors to ensure alpha is set
776 setMeshColor(m_animated_meshnode->getMesh(), video::SColor(0xFFFFFFFF));
778 setAnimatedMeshColor(m_animated_meshnode, video::SColor(0xFFFFFFFF));
780 setSceneNodeMaterial(m_animated_meshnode);
782 m_animated_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
783 m_prop.backface_culling);
785 errorstream<<"GenericCAO::addToScene(): Could not load mesh "<<m_prop.mesh<<std::endl;
786 } else if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
789 if (m_prop.wield_item.empty()) {
790 // Old format, only textures are specified.
791 infostream << "textures: " << m_prop.textures.size() << std::endl;
792 if (!m_prop.textures.empty()) {
793 infostream << "textures[0]: " << m_prop.textures[0]
795 IItemDefManager *idef = m_client->idef();
796 item = ItemStack(m_prop.textures[0], 1, 0, idef);
799 infostream << "serialized form: " << m_prop.wield_item << std::endl;
800 item.deSerialize(m_prop.wield_item, m_client->idef());
802 m_wield_meshnode = new WieldMeshSceneNode(
803 RenderingEngine::get_scene_manager(), -1);
804 m_wield_meshnode->setItem(item, m_client,
805 (m_prop.visual == "wielditem"));
807 m_wield_meshnode->setScale(m_prop.visual_size / 2.0f);
808 m_wield_meshnode->setColor(video::SColor(0xFFFFFFFF));
810 infostream<<"GenericCAO::addToScene(): \""<<m_prop.visual
811 <<"\" not supported"<<std::endl;
814 /* don't update while punch texture modifier is active */
815 if (m_reset_textures_timer < 0)
816 updateTextures(m_current_texture_modifier);
818 scene::ISceneNode *node = getSceneNode();
820 if (node && m_matrixnode)
821 node->setParent(m_matrixnode);
827 updateBonePosition();
829 setNodeLight(m_last_light);
833 void GenericCAO::updateLight(u32 day_night_ratio)
842 u16 npos = getLightPosition(pos);
843 for (u16 i = 0; i < npos; i++) {
845 MapNode n = m_env->getMap().getNode(pos[i], &this_ok);
847 u8 this_light = n.getLightBlend(day_night_ratio, m_client->ndef());
848 light_at_pos = MYMAX(light_at_pos, this_light);
853 light_at_pos = blend_light(day_night_ratio, LIGHT_SUN, 0);
855 u8 light = decode_light(light_at_pos + m_glow);
856 if (g_settings->getBool("fullbright"))
858 if (light != m_last_light) {
859 m_last_light = light;
864 void GenericCAO::setNodeLight(u8 light)
866 video::SColor color(255, light, light, light);
868 if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
869 if (m_wield_meshnode)
870 m_wield_meshnode->setNodeLightColor(color);
874 if (m_enable_shaders) {
875 if (m_prop.visual == "upright_sprite") {
879 scene::IMesh *mesh = m_meshnode->getMesh();
880 for (u32 i = 0; i < mesh->getMeshBufferCount(); ++i) {
881 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
882 buf->getMaterial().EmissiveColor = color;
885 scene::ISceneNode *node = getSceneNode();
889 for (u32 i = 0; i < node->getMaterialCount(); ++i) {
890 video::SMaterial &material = node->getMaterial(i);
891 material.EmissiveColor = color;
896 setMeshColor(m_meshnode->getMesh(), color);
897 } else if (m_animated_meshnode) {
898 setAnimatedMeshColor(m_animated_meshnode, color);
899 } else if (m_spritenode) {
900 m_spritenode->setColor(color);
905 u16 GenericCAO::getLightPosition(v3s16 *pos)
907 const auto &box = m_prop.collisionbox;
908 pos[0] = floatToInt(m_position + box.MinEdge * BS, BS);
909 pos[1] = floatToInt(m_position + box.MaxEdge * BS, BS);
911 // Skip center pos if it falls into the same node as Min or MaxEdge
912 if ((box.MaxEdge - box.MinEdge).getLengthSQ() < 3.0f)
914 pos[2] = floatToInt(m_position + box.getCenter() * BS, BS);
918 void GenericCAO::updateMarker()
920 if (!m_client->getMinimap())
923 if (!m_prop.show_on_minimap) {
925 m_client->getMinimap()->removeMarker(&m_marker);
932 scene::ISceneNode *node = getSceneNode();
935 m_marker = m_client->getMinimap()->addMarker(node);
938 void GenericCAO::updateNametag()
940 if (m_is_local_player && ! g_settings->getBool("freecam")) // No nametag for local player
943 if (m_prop.nametag.empty()) {
946 m_client->getCamera()->removeNametag(m_nametag);
952 scene::ISceneNode *node = getSceneNode();
957 pos.Y = m_prop.selectionbox.MaxEdge.Y + 0.3f;
960 m_nametag = m_client->getCamera()->addNametag(node,
961 m_prop.nametag, m_prop.nametag_color, pos);
964 m_nametag->nametag_text = m_prop.nametag;
965 m_nametag->nametag_color = m_prop.nametag_color;
966 m_nametag->nametag_pos = pos;
970 void GenericCAO::updateNodePos()
972 if (getParent() != NULL)
975 scene::ISceneNode *node = getSceneNode();
978 v3s16 camera_offset = m_env->getCameraOffset();
979 v3f pos = pos_translator.val_current -
980 intToFloat(camera_offset, BS);
981 getPosRotMatrix().setTranslation(pos);
982 if (node != m_spritenode) { // rotate if not a sprite
983 v3f rot = m_is_local_player ? -m_rotation : -rot_translator.val_current;
984 setPitchYawRoll(getPosRotMatrix(), rot);
989 void GenericCAO::step(float dtime, ClientEnvironment *env)
991 // Handle model animations and update positions instantly to prevent lags
992 if (m_is_local_player) {
993 LocalPlayer *player = m_env->getLocalPlayer();
994 m_position = player->getLegitPosition();
995 pos_translator.val_current = m_position;
996 if (! g_settings->getBool("freecam")) {
997 m_rotation.Y = wrapDegrees_0_360(player->getYaw());
998 rot_translator.val_current = m_rotation;
1002 int old_anim = player->last_animation;
1003 float old_anim_speed = player->last_animation_speed;
1004 m_velocity = v3f(0,0,0);
1005 m_acceleration = v3f(0,0,0);
1006 const PlayerControl &controls = player->getPlayerControl();
1008 bool walking = false;
1009 if ((controls.up || controls.down || controls.left || controls.right ||
1010 controls.forw_move_joystick_axis != 0.f ||
1011 controls.sidew_move_joystick_axis != 0.f) && ! g_settings->getBool("freecam"))
1014 f32 new_speed = player->local_animation_speed;
1015 v2s32 new_anim = v2s32(0,0);
1016 bool allow_update = false;
1018 // increase speed if using fast or flying fast
1019 if((g_settings->getBool("fast_move") &&
1020 m_client->checkLocalPrivilege("fast")) &&
1022 (!player->touching_ground &&
1023 g_settings->getBool("free_move") &&
1024 m_client->checkLocalPrivilege("fly"))))
1026 // slowdown speed if sneeking
1027 if (controls.sneak && walking && ! g_settings->getBool("no_slow"))
1030 if (walking && (controls.dig || controls.place)) {
1031 new_anim = player->local_animations[3];
1032 player->last_animation = WD_ANIM;
1033 } else if (walking) {
1034 new_anim = player->local_animations[1];
1035 player->last_animation = WALK_ANIM;
1036 } else if (controls.dig || controls.place) {
1037 new_anim = player->local_animations[2];
1038 player->last_animation = DIG_ANIM;
1041 // Apply animations if input detected and not attached
1042 // or set idle animation
1043 if ((new_anim.X + new_anim.Y) > 0 && !getParent()) {
1044 allow_update = true;
1045 m_animation_range = new_anim;
1046 m_animation_speed = new_speed;
1047 player->last_animation_speed = m_animation_speed;
1049 player->last_animation = NO_ANIM;
1051 if (old_anim != NO_ANIM) {
1052 m_animation_range = player->local_animations[0];
1057 // Update local player animations
1058 if ((player->last_animation != old_anim ||
1059 m_animation_speed != old_anim_speed) &&
1060 player->last_animation != NO_ANIM && allow_update)
1066 if (m_visuals_expired && m_smgr) {
1067 m_visuals_expired = false;
1069 // Attachments, part 1: All attached objects must be unparented first,
1070 // or Irrlicht causes a segmentation fault
1071 for (u16 cao_id : m_attachment_child_ids) {
1072 ClientActiveObject *obj = m_env->getActiveObject(cao_id);
1074 scene::ISceneNode *child_node = obj->getSceneNode();
1075 // The node's parent is always an IDummyTraformationSceneNode,
1076 // so we need to reparent that one instead.
1078 child_node->getParent()->setParent(m_smgr->getRootSceneNode());
1082 removeFromScene(false);
1083 addToScene(m_client->tsrc());
1085 // Attachments, part 2: Now that the parent has been refreshed, put its attachments back
1086 for (u16 cao_id : m_attachment_child_ids) {
1087 ClientActiveObject *obj = m_env->getActiveObject(cao_id);
1089 obj->updateAttachments();
1093 // Make sure m_is_visible is always applied
1094 scene::ISceneNode *node = getSceneNode();
1096 node->setVisible(m_is_visible);
1098 if(getParent() != NULL) // Attachments should be glued to their parent by Irrlicht
1100 // Set these for later
1101 m_position = getPosition();
1102 m_velocity = v3f(0,0,0);
1103 m_acceleration = v3f(0,0,0);
1104 pos_translator.val_current = m_position;
1105 pos_translator.val_target = m_position;
1107 rot_translator.translate(dtime);
1108 v3f lastpos = pos_translator.val_current;
1112 aabb3f box = m_prop.collisionbox;
1115 collisionMoveResult moveresult;
1116 f32 pos_max_d = BS*0.125; // Distance per iteration
1117 v3f p_pos = m_position;
1118 v3f p_velocity = m_velocity;
1119 moveresult = collisionMoveSimple(env,env->getGameDef(),
1120 pos_max_d, box, m_prop.stepheight, dtime,
1121 &p_pos, &p_velocity, m_acceleration,
1122 this, m_prop.collideWithObjects);
1125 m_velocity = p_velocity;
1127 bool is_end_position = moveresult.collides;
1128 pos_translator.update(m_position, is_end_position, dtime);
1130 m_position += dtime * m_velocity + 0.5 * dtime * dtime * m_acceleration;
1131 m_velocity += dtime * m_acceleration;
1132 pos_translator.update(m_position, pos_translator.aim_is_end,
1133 pos_translator.anim_time);
1135 pos_translator.translate(dtime);
1138 float moved = lastpos.getDistanceFrom(pos_translator.val_current);
1139 m_step_distance_counter += moved;
1140 if (m_step_distance_counter > 1.5f * BS) {
1141 m_step_distance_counter = 0.0f;
1142 if (!m_is_local_player && m_prop.makes_footstep_sound) {
1143 const NodeDefManager *ndef = m_client->ndef();
1144 v3s16 p = floatToInt(getPosition() +
1145 v3f(0.0f, (m_prop.collisionbox.MinEdge.Y - 0.5f) * BS, 0.0f), BS);
1146 MapNode n = m_env->getMap().getNode(p);
1147 SimpleSoundSpec spec = ndef->get(n).sound_footstep;
1148 // Reduce footstep gain, as non-local-player footsteps are
1151 m_client->sound()->playSoundAt(spec, false, getPosition());
1156 m_anim_timer += dtime;
1157 if(m_anim_timer >= m_anim_framelength)
1159 m_anim_timer -= m_anim_framelength;
1161 if(m_anim_frame >= m_anim_num_frames)
1167 if(m_reset_textures_timer >= 0)
1169 m_reset_textures_timer -= dtime;
1170 if(m_reset_textures_timer <= 0) {
1171 m_reset_textures_timer = -1;
1172 updateTextures(m_previous_texture_modifier);
1176 if (!getParent() && std::fabs(m_prop.automatic_rotate) > 0.001) {
1177 // This is the child node's rotation. It is only used for automatic_rotate.
1178 v3f local_rot = node->getRotation();
1179 local_rot.Y = modulo360f(local_rot.Y - dtime * core::RADTODEG *
1180 m_prop.automatic_rotate);
1181 node->setRotation(local_rot);
1184 if (!getParent() && m_prop.automatic_face_movement_dir &&
1185 (fabs(m_velocity.Z) > 0.001 || fabs(m_velocity.X) > 0.001)) {
1186 float target_yaw = atan2(m_velocity.Z, m_velocity.X) * 180 / M_PI
1187 + m_prop.automatic_face_movement_dir_offset;
1188 float max_rotation_per_sec =
1189 m_prop.automatic_face_movement_max_rotation_per_sec;
1191 if (max_rotation_per_sec > 0) {
1192 wrappedApproachShortest(m_rotation.Y, target_yaw,
1193 dtime * max_rotation_per_sec, 360.f);
1195 // Negative values of max_rotation_per_sec mean disabled.
1196 m_rotation.Y = target_yaw;
1199 rot_translator.val_current = m_rotation;
1203 if (m_animated_meshnode) {
1204 // Everything must be updated; the whole transform
1205 // chain as well as the animated mesh node.
1206 // Otherwise, bone attachments would be relative to
1207 // a position that's one frame old.
1209 updatePositionRecursive(m_matrixnode);
1210 m_animated_meshnode->updateAbsolutePosition();
1211 m_animated_meshnode->animateJoints();
1212 updateBonePosition();
1216 void GenericCAO::updateTexturePos()
1220 scene::ICameraSceneNode* camera =
1221 m_spritenode->getSceneManager()->getActiveCamera();
1224 v3f cam_to_entity = m_spritenode->getAbsolutePosition()
1225 - camera->getAbsolutePosition();
1226 cam_to_entity.normalize();
1228 int row = m_tx_basepos.Y;
1229 int col = m_tx_basepos.X;
1231 // Yawpitch goes rightwards
1232 if (m_tx_select_horiz_by_yawpitch) {
1233 if (cam_to_entity.Y > 0.75)
1235 else if (cam_to_entity.Y < -0.75)
1239 atan2(cam_to_entity.Z, cam_to_entity.X) / M_PI * 180.;
1240 float dir = mob_dir - m_rotation.Y;
1241 dir = wrapDegrees_180(dir);
1242 if (std::fabs(wrapDegrees_180(dir - 0)) <= 45.1f)
1244 else if(std::fabs(wrapDegrees_180(dir - 90)) <= 45.1f)
1246 else if(std::fabs(wrapDegrees_180(dir - 180)) <= 45.1f)
1248 else if(std::fabs(wrapDegrees_180(dir + 90)) <= 45.1f)
1255 // Animation goes downwards
1256 row += m_anim_frame;
1258 float txs = m_tx_size.X;
1259 float tys = m_tx_size.Y;
1260 setBillboardTextureMatrix(m_spritenode, txs, tys, col, row);
1263 else if (m_meshnode) {
1264 if (m_prop.visual == "upright_sprite") {
1265 int row = m_tx_basepos.Y;
1266 int col = m_tx_basepos.X;
1268 // Animation goes downwards
1269 row += m_anim_frame;
1271 const auto &tx = m_tx_size;
1272 v2f t[4] = { // cf. vertices in GenericCAO::addToScene()
1273 tx * v2f(col+1, row+1),
1274 tx * v2f(col, row+1),
1276 tx * v2f(col+1, row),
1278 auto mesh = m_meshnode->getMesh();
1279 setMeshBufferTextureCoords(mesh->getMeshBuffer(0), t, 4);
1280 setMeshBufferTextureCoords(mesh->getMeshBuffer(1), t, 4);
1285 // Do not pass by reference, see header.
1286 void GenericCAO::updateTextures(std::string mod)
1288 ITextureSource *tsrc = m_client->tsrc();
1290 bool use_trilinear_filter = g_settings->getBool("trilinear_filter");
1291 bool use_bilinear_filter = g_settings->getBool("bilinear_filter");
1292 bool use_anisotropic_filter = g_settings->getBool("anisotropic_filter");
1294 m_previous_texture_modifier = m_current_texture_modifier;
1295 m_current_texture_modifier = mod;
1296 m_glow = m_prop.glow;
1299 if (m_prop.visual == "sprite") {
1300 std::string texturestring = "unknown_node.png";
1301 if (!m_prop.textures.empty())
1302 texturestring = m_prop.textures[0];
1303 texturestring += mod;
1304 m_spritenode->getMaterial(0).MaterialType = m_material_type;
1305 m_spritenode->getMaterial(0).MaterialTypeParam = 0.5f;
1306 m_spritenode->setMaterialTexture(0,
1307 tsrc->getTextureForMesh(texturestring));
1309 // This allows setting per-material colors. However, until a real lighting
1310 // system is added, the code below will have no effect. Once MineTest
1311 // has directional lighting, it should work automatically.
1312 if (!m_prop.colors.empty()) {
1313 m_spritenode->getMaterial(0).AmbientColor = m_prop.colors[0];
1314 m_spritenode->getMaterial(0).DiffuseColor = m_prop.colors[0];
1315 m_spritenode->getMaterial(0).SpecularColor = m_prop.colors[0];
1318 m_spritenode->getMaterial(0).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1319 m_spritenode->getMaterial(0).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1320 m_spritenode->getMaterial(0).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1324 else if (m_animated_meshnode) {
1325 if (m_prop.visual == "mesh") {
1326 for (u32 i = 0; i < m_prop.textures.size() &&
1327 i < m_animated_meshnode->getMaterialCount(); ++i) {
1328 std::string texturestring = m_prop.textures[i];
1329 if (texturestring.empty())
1330 continue; // Empty texture string means don't modify that material
1331 texturestring += mod;
1332 video::ITexture* texture = tsrc->getTextureForMesh(texturestring);
1334 errorstream<<"GenericCAO::updateTextures(): Could not load texture "<<texturestring<<std::endl;
1338 // Set material flags and texture
1339 video::SMaterial& material = m_animated_meshnode->getMaterial(i);
1340 material.MaterialType = m_material_type;
1341 material.MaterialTypeParam = 0.5f;
1342 material.TextureLayer[0].Texture = texture;
1343 material.setFlag(video::EMF_LIGHTING, true);
1344 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1345 material.setFlag(video::EMF_BACK_FACE_CULLING, m_prop.backface_culling);
1347 // don't filter low-res textures, makes them look blurry
1348 // player models have a res of 64
1349 const core::dimension2d<u32> &size = texture->getOriginalSize();
1350 const u32 res = std::min(size.Height, size.Width);
1351 use_trilinear_filter &= res > 64;
1352 use_bilinear_filter &= res > 64;
1354 m_animated_meshnode->getMaterial(i)
1355 .setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1356 m_animated_meshnode->getMaterial(i)
1357 .setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1358 m_animated_meshnode->getMaterial(i)
1359 .setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1361 for (u32 i = 0; i < m_prop.colors.size() &&
1362 i < m_animated_meshnode->getMaterialCount(); ++i)
1364 // This allows setting per-material colors. However, until a real lighting
1365 // system is added, the code below will have no effect. Once MineTest
1366 // has directional lighting, it should work automatically.
1367 m_animated_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1368 m_animated_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1369 m_animated_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1374 else if (m_meshnode) {
1375 if(m_prop.visual == "cube")
1377 for (u32 i = 0; i < 6; ++i)
1379 std::string texturestring = "unknown_node.png";
1380 if(m_prop.textures.size() > i)
1381 texturestring = m_prop.textures[i];
1382 texturestring += mod;
1385 // Set material flags and texture
1386 video::SMaterial& material = m_meshnode->getMaterial(i);
1387 material.MaterialType = m_material_type;
1388 material.MaterialTypeParam = 0.5f;
1389 material.setFlag(video::EMF_LIGHTING, false);
1390 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1391 material.setTexture(0,
1392 tsrc->getTextureForMesh(texturestring));
1393 material.getTextureMatrix(0).makeIdentity();
1395 // This allows setting per-material colors. However, until a real lighting
1396 // system is added, the code below will have no effect. Once MineTest
1397 // has directional lighting, it should work automatically.
1398 if(m_prop.colors.size() > i)
1400 m_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1401 m_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1402 m_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1405 m_meshnode->getMaterial(i).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1406 m_meshnode->getMaterial(i).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1407 m_meshnode->getMaterial(i).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1409 } else if (m_prop.visual == "upright_sprite") {
1410 scene::IMesh *mesh = m_meshnode->getMesh();
1412 std::string tname = "unknown_object.png";
1413 if (!m_prop.textures.empty())
1414 tname = m_prop.textures[0];
1416 scene::IMeshBuffer *buf = mesh->getMeshBuffer(0);
1417 buf->getMaterial().setTexture(0,
1418 tsrc->getTextureForMesh(tname));
1420 // This allows setting per-material colors. However, until a real lighting
1421 // system is added, the code below will have no effect. Once MineTest
1422 // has directional lighting, it should work automatically.
1423 if(!m_prop.colors.empty()) {
1424 buf->getMaterial().AmbientColor = m_prop.colors[0];
1425 buf->getMaterial().DiffuseColor = m_prop.colors[0];
1426 buf->getMaterial().SpecularColor = m_prop.colors[0];
1429 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1430 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1431 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1434 std::string tname = "unknown_object.png";
1435 if (m_prop.textures.size() >= 2)
1436 tname = m_prop.textures[1];
1437 else if (!m_prop.textures.empty())
1438 tname = m_prop.textures[0];
1440 scene::IMeshBuffer *buf = mesh->getMeshBuffer(1);
1441 buf->getMaterial().setTexture(0,
1442 tsrc->getTextureForMesh(tname));
1444 // This allows setting per-material colors. However, until a real lighting
1445 // system is added, the code below will have no effect. Once MineTest
1446 // has directional lighting, it should work automatically.
1447 if (m_prop.colors.size() >= 2) {
1448 buf->getMaterial().AmbientColor = m_prop.colors[1];
1449 buf->getMaterial().DiffuseColor = m_prop.colors[1];
1450 buf->getMaterial().SpecularColor = m_prop.colors[1];
1451 } else if (!m_prop.colors.empty()) {
1452 buf->getMaterial().AmbientColor = m_prop.colors[0];
1453 buf->getMaterial().DiffuseColor = m_prop.colors[0];
1454 buf->getMaterial().SpecularColor = m_prop.colors[0];
1457 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1458 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1459 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1461 // Set mesh color (only if lighting is disabled)
1462 if (!m_prop.colors.empty() && m_glow < 0)
1463 setMeshColor(mesh, m_prop.colors[0]);
1466 // Prevent showing the player after changing texture
1467 if (m_is_local_player)
1468 updateMeshCulling();
1471 void GenericCAO::updateAnimation()
1473 if (!m_animated_meshnode)
1476 if (m_animated_meshnode->getStartFrame() != m_animation_range.X ||
1477 m_animated_meshnode->getEndFrame() != m_animation_range.Y)
1478 m_animated_meshnode->setFrameLoop(m_animation_range.X, m_animation_range.Y);
1479 if (m_animated_meshnode->getAnimationSpeed() != m_animation_speed)
1480 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1481 m_animated_meshnode->setTransitionTime(m_animation_blend);
1482 // Requires Irrlicht 1.8 or greater
1483 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR > 1
1484 if (m_animated_meshnode->getLoopMode() != m_animation_loop)
1485 m_animated_meshnode->setLoopMode(m_animation_loop);
1489 void GenericCAO::updateAnimationSpeed()
1491 if (!m_animated_meshnode)
1494 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1497 void GenericCAO::updateBonePosition()
1499 if (m_bone_position.empty() || !m_animated_meshnode)
1502 m_animated_meshnode->setJointMode(irr::scene::EJUOR_CONTROL); // To write positions to the mesh on render
1503 for (auto &it : m_bone_position) {
1504 std::string bone_name = it.first;
1505 irr::scene::IBoneSceneNode* bone = m_animated_meshnode->getJointNode(bone_name.c_str());
1507 bone->setPosition(it.second.X);
1508 bone->setRotation(it.second.Y);
1512 // search through bones to find mistakenly rotated bones due to bug in Irrlicht
1513 for (u32 i = 0; i < m_animated_meshnode->getJointCount(); ++i) {
1514 irr::scene::IBoneSceneNode *bone = m_animated_meshnode->getJointNode(i);
1518 //If bone is manually positioned there is no need to perform the bug check
1520 for (auto &it : m_bone_position) {
1521 if (it.first == bone->getName()) {
1529 // Workaround for Irrlicht bug
1530 // We check each bone to see if it has been rotated ~180deg from its expected position due to a bug in Irricht
1531 // when using EJUOR_CONTROL joint control. If the bug is detected we update the bone to the proper position
1532 // and update the bones transformation.
1533 v3f bone_rot = bone->getRelativeTransformation().getRotationDegrees();
1534 float offset = fabsf(bone_rot.X - bone->getRotation().X);
1535 if (offset > 179.9f && offset < 180.1f) {
1536 bone->setRotation(bone_rot);
1537 bone->updateAbsolutePosition();
1540 // The following is needed for set_bone_pos to propagate to
1541 // attached objects correctly.
1542 // Irrlicht ought to do this, but doesn't when using EJUOR_CONTROL.
1543 for (u32 i = 0; i < m_animated_meshnode->getJointCount(); ++i) {
1544 auto bone = m_animated_meshnode->getJointNode(i);
1545 // Look for the root bone.
1546 if (bone && bone->getParent() == m_animated_meshnode) {
1547 // Update entire skeleton.
1548 bone->updateAbsolutePositionOfAllChildren();
1554 void GenericCAO::updateAttachments()
1556 ClientActiveObject *parent = getParent();
1558 m_attached_to_local = parent && parent->isLocalPlayer();
1561 Following cases exist:
1562 m_attachment_parent_id == 0 && !parent
1563 This object is not attached
1564 m_attachment_parent_id != 0 && parent
1565 This object is attached
1566 m_attachment_parent_id != 0 && !parent
1567 This object will be attached as soon the parent is known
1568 m_attachment_parent_id == 0 && parent
1572 if (!parent) { // Detach or don't attach
1574 v3s16 camera_offset = m_env->getCameraOffset();
1575 v3f old_pos = getPosition();
1577 m_matrixnode->setParent(m_smgr->getRootSceneNode());
1578 getPosRotMatrix().setTranslation(old_pos - intToFloat(camera_offset, BS));
1579 m_matrixnode->updateAbsolutePosition();
1584 parent->updateAttachments();
1585 scene::ISceneNode *parent_node = parent->getSceneNode();
1586 scene::IAnimatedMeshSceneNode *parent_animated_mesh_node =
1587 parent->getAnimatedMeshSceneNode();
1588 if (parent_animated_mesh_node && !m_attachment_bone.empty()) {
1589 parent_node = parent_animated_mesh_node->getJointNode(m_attachment_bone.c_str());
1592 if (m_matrixnode && parent_node) {
1593 m_matrixnode->setParent(parent_node);
1594 parent_node->updateAbsolutePosition();
1595 getPosRotMatrix().setTranslation(m_attachment_position);
1596 //setPitchYawRoll(getPosRotMatrix(), m_attachment_rotation);
1597 // use Irrlicht eulers instead
1598 getPosRotMatrix().setRotationDegrees(m_attachment_rotation);
1599 m_matrixnode->updateAbsolutePosition();
1604 bool GenericCAO::visualExpiryRequired(const ObjectProperties &new_) const
1606 const ObjectProperties &old = m_prop;
1607 /* Visuals do not need to be expired for:
1608 * - nametag props: handled by updateNametag()
1609 * - textures: handled by updateTextures()
1610 * - sprite props: handled by updateTexturePos()
1611 * - glow: handled by updateLight()
1612 * - any other properties that do not change appearance
1615 bool uses_legacy_texture = new_.wield_item.empty() &&
1616 (new_.visual == "wielditem" || new_.visual == "item");
1617 // Ordered to compare primitive types before std::vectors
1618 return old.backface_culling != new_.backface_culling ||
1619 old.is_visible != new_.is_visible ||
1620 old.mesh != new_.mesh ||
1621 old.shaded != new_.shaded ||
1622 old.use_texture_alpha != new_.use_texture_alpha ||
1623 old.visual != new_.visual ||
1624 old.visual_size != new_.visual_size ||
1625 old.wield_item != new_.wield_item ||
1626 old.colors != new_.colors ||
1627 (uses_legacy_texture && old.textures != new_.textures);
1630 void GenericCAO::processMessage(const std::string &data)
1632 //infostream<<"GenericCAO: Got message"<<std::endl;
1633 std::istringstream is(data, std::ios::binary);
1635 u8 cmd = readU8(is);
1636 if (cmd == AO_CMD_SET_PROPERTIES) {
1637 ObjectProperties newprops;
1638 newprops.show_on_minimap = m_is_player; // default
1640 newprops.deSerialize(is);
1642 // Check what exactly changed
1643 bool expire_visuals = visualExpiryRequired(newprops);
1644 bool textures_changed = m_prop.textures != newprops.textures;
1647 m_prop = std::move(newprops);
1649 m_selection_box = m_prop.selectionbox;
1650 m_selection_box.MinEdge *= BS;
1651 m_selection_box.MaxEdge *= BS;
1653 m_tx_size.X = 1.0f / m_prop.spritediv.X;
1654 m_tx_size.Y = 1.0f / m_prop.spritediv.Y;
1656 if(!m_initial_tx_basepos_set){
1657 m_initial_tx_basepos_set = true;
1658 m_tx_basepos = m_prop.initial_sprite_basepos;
1660 if (m_is_local_player) {
1661 LocalPlayer *player = m_env->getLocalPlayer();
1662 player->makes_footstep_sound = m_prop.makes_footstep_sound;
1663 aabb3f collision_box = m_prop.collisionbox;
1664 collision_box.MinEdge *= BS;
1665 collision_box.MaxEdge *= BS;
1666 player->setCollisionbox(collision_box);
1667 player->setEyeHeight(m_prop.eye_height);
1668 player->setZoomFOV(m_prop.zoom_fov);
1671 if ((m_is_player && !m_is_local_player) && m_prop.nametag.empty())
1672 m_prop.nametag = m_name;
1673 if (m_is_local_player)
1674 m_prop.show_on_minimap = false;
1676 if (expire_visuals) {
1679 infostream << "GenericCAO: properties updated but expiring visuals"
1680 << " not necessary" << std::endl;
1681 if (textures_changed) {
1682 // don't update while punch texture modifier is active
1683 if (m_reset_textures_timer < 0)
1684 updateTextures(m_current_texture_modifier);
1689 } else if (cmd == AO_CMD_UPDATE_POSITION) {
1690 // Not sent by the server if this object is an attachment.
1691 // We might however get here if the server notices the object being detached before the client.
1692 m_position = readV3F32(is);
1693 m_velocity = readV3F32(is);
1694 m_acceleration = readV3F32(is);
1695 m_rotation = readV3F32(is);
1697 m_rotation = wrapDegrees_0_360_v3f(m_rotation);
1698 bool do_interpolate = readU8(is);
1699 bool is_end_position = readU8(is);
1700 float update_interval = readF32(is);
1702 // Place us a bit higher if we're physical, to not sink into
1703 // the ground due to sucky collision detection...
1705 m_position += v3f(0,0.002,0);
1707 if(getParent() != NULL) // Just in case
1712 if(!m_prop.physical)
1713 pos_translator.update(m_position, is_end_position, update_interval);
1715 pos_translator.init(m_position);
1717 rot_translator.update(m_rotation, false, update_interval);
1719 } else if (cmd == AO_CMD_SET_TEXTURE_MOD) {
1720 std::string mod = deSerializeString16(is);
1722 // immediately reset a engine issued texture modifier if a mod sends a different one
1723 if (m_reset_textures_timer > 0) {
1724 m_reset_textures_timer = -1;
1725 updateTextures(m_previous_texture_modifier);
1727 updateTextures(mod);
1728 } else if (cmd == AO_CMD_SET_SPRITE) {
1729 v2s16 p = readV2S16(is);
1730 int num_frames = readU16(is);
1731 float framelength = readF32(is);
1732 bool select_horiz_by_yawpitch = readU8(is);
1735 m_anim_num_frames = num_frames;
1736 m_anim_framelength = framelength;
1737 m_tx_select_horiz_by_yawpitch = select_horiz_by_yawpitch;
1740 } else if (cmd == AO_CMD_SET_PHYSICS_OVERRIDE) {
1741 float override_speed = readF32(is);
1742 float override_jump = readF32(is);
1743 float override_gravity = readF32(is);
1744 // these are sent inverted so we get true when the server sends nothing
1745 bool sneak = !readU8(is);
1746 bool sneak_glitch = !readU8(is);
1747 bool new_move = !readU8(is);
1750 if(m_is_local_player)
1752 Client *client = m_env->getGameDef();
1754 if (client->modsLoaded() && client->getScript()->on_recieve_physics_override(override_speed, override_jump, override_gravity, sneak, sneak_glitch, new_move))
1757 LocalPlayer *player = m_env->getLocalPlayer();
1758 player->physics_override_speed = override_speed;
1759 player->physics_override_jump = override_jump;
1760 player->physics_override_gravity = override_gravity;
1761 player->physics_override_sneak = sneak;
1762 player->physics_override_sneak_glitch = sneak_glitch;
1763 player->physics_override_new_move = new_move;
1765 } else if (cmd == AO_CMD_SET_ANIMATION) {
1766 // TODO: change frames send as v2s32 value
1767 v2f range = readV2F32(is);
1768 if (!m_is_local_player) {
1769 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1770 m_animation_speed = readF32(is);
1771 m_animation_blend = readF32(is);
1772 // these are sent inverted so we get true when the server sends nothing
1773 m_animation_loop = !readU8(is);
1776 LocalPlayer *player = m_env->getLocalPlayer();
1777 if(player->last_animation == NO_ANIM)
1779 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1780 m_animation_speed = readF32(is);
1781 m_animation_blend = readF32(is);
1782 // these are sent inverted so we get true when the server sends nothing
1783 m_animation_loop = !readU8(is);
1785 // update animation only if local animations present
1786 // and received animation is unknown (except idle animation)
1787 bool is_known = false;
1788 for (int i = 1;i<4;i++)
1790 if(m_animation_range.Y == player->local_animations[i].Y)
1794 (player->local_animations[1].Y + player->local_animations[2].Y < 1))
1799 } else if (cmd == AO_CMD_SET_ANIMATION_SPEED) {
1800 m_animation_speed = readF32(is);
1801 updateAnimationSpeed();
1802 } else if (cmd == AO_CMD_SET_BONE_POSITION) {
1803 std::string bone = deSerializeString16(is);
1804 v3f position = readV3F32(is);
1805 v3f rotation = readV3F32(is);
1806 m_bone_position[bone] = core::vector2d<v3f>(position, rotation);
1808 // updateBonePosition(); now called every step
1809 } else if (cmd == AO_CMD_ATTACH_TO) {
1810 u16 parent_id = readS16(is);
1811 std::string bone = deSerializeString16(is);
1812 v3f position = readV3F32(is);
1813 v3f rotation = readV3F32(is);
1814 bool force_visible = readU8(is); // Returns false for EOF
1816 setAttachment(parent_id, bone, position, rotation, force_visible);
1817 } else if (cmd == AO_CMD_PUNCHED) {
1818 u16 result_hp = readU16(is);
1820 // Use this instead of the send damage to not interfere with prediction
1821 s32 damage = (s32)m_hp - (s32)result_hp;
1825 if (m_is_local_player)
1826 m_env->getLocalPlayer()->hp = m_hp;
1832 // TODO: Execute defined fast response
1833 // As there is no definition, make a smoke puff
1834 ClientSimpleObject *simple = createSmokePuff(
1835 m_smgr, m_env, m_position,
1836 v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
1837 m_env->addSimpleObject(simple);
1838 } else if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
1839 m_reset_textures_timer = 0.05;
1841 m_reset_textures_timer += 0.05 * damage;
1842 updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
1847 // Same as 'Server::DiePlayer'
1848 clearParentAttachment();
1849 // Same as 'ObjectRef::l_remove'
1851 clearChildAttachments();
1853 } else if (cmd == AO_CMD_UPDATE_ARMOR_GROUPS) {
1854 m_armor_groups.clear();
1855 int armor_groups_size = readU16(is);
1856 for(int i=0; i<armor_groups_size; i++)
1858 std::string name = deSerializeString16(is);
1859 int rating = readS16(is);
1860 m_armor_groups[name] = rating;
1862 } else if (cmd == AO_CMD_SPAWN_INFANT) {
1863 u16 child_id = readU16(is);
1864 u8 type = readU8(is); // maybe this will be useful later
1867 addAttachmentChild(child_id);
1868 } else if (cmd == AO_CMD_OBSOLETE1) {
1869 // Don't do anything and also don't log a warning
1871 warningstream << FUNCTION_NAME
1872 << ": unknown command or outdated client \""
1873 << +cmd << "\"" << std::endl;
1877 /* \pre punchitem != NULL
1879 bool GenericCAO::directReportPunch(v3f dir, const ItemStack *punchitem,
1880 float time_from_last_punch)
1882 assert(punchitem); // pre-condition
1883 const ToolCapabilities *toolcap =
1884 &punchitem->getToolCapabilities(m_client->idef());
1885 PunchDamageResult result = getPunchDamage(
1889 time_from_last_punch);
1891 if(result.did_punch && result.damage != 0)
1893 if(result.damage < m_hp)
1895 m_hp -= result.damage;
1898 // TODO: Execute defined fast response
1899 // As there is no definition, make a smoke puff
1900 ClientSimpleObject *simple = createSmokePuff(
1901 m_smgr, m_env, m_position,
1902 v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
1903 m_env->addSimpleObject(simple);
1905 if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
1906 m_reset_textures_timer = 0.05;
1907 if (result.damage >= 2)
1908 m_reset_textures_timer += 0.05 * result.damage;
1909 updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
1916 std::string GenericCAO::debugInfoText()
1918 std::ostringstream os(std::ios::binary);
1919 os<<"GenericCAO hp="<<m_hp<<"\n";
1921 for(ItemGroupList::const_iterator i = m_armor_groups.begin();
1922 i != m_armor_groups.end(); ++i)
1924 os<<i->first<<"="<<i->second<<", ";
1930 void GenericCAO::updateMeshCulling()
1932 if (!m_is_local_player)
1935 const bool hidden = m_client->getCamera()->getCameraMode() == CAMERA_MODE_FIRST;
1937 if (m_meshnode && m_prop.visual == "upright_sprite") {
1938 u32 buffers = m_meshnode->getMesh()->getMeshBufferCount();
1939 for (u32 i = 0; i < buffers; i++) {
1940 video::SMaterial &mat = m_meshnode->getMesh()->getMeshBuffer(i)->getMaterial();
1941 // upright sprite has no backface culling
1942 mat.setFlag(video::EMF_FRONT_FACE_CULLING, hidden);
1947 irr::scene::ISceneNode *node = getSceneNode();
1952 // Hide the mesh by culling both front and
1953 // back faces. Serious hackyness but it works for our
1954 // purposes. This also preserves the skeletal armature.
1955 node->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
1957 node->setMaterialFlag(video::EMF_FRONT_FACE_CULLING,
1960 // Restore mesh visibility.
1961 node->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
1962 m_prop.backface_culling);
1963 node->setMaterialFlag(video::EMF_FRONT_FACE_CULLING,
1969 GenericCAO proto_GenericCAO(NULL, NULL);