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 <IMeshManipulator.h>
24 #include <IAnimatedMeshSceneNode.h>
25 #include "client/client.h"
26 #include "client/renderingengine.h"
27 #include "client/sound.h"
28 #include "client/tile.h"
29 #include "util/basic_macros.h"
30 #include "util/numeric.h"
31 #include "util/serialize.h"
32 #include "camera.h" // CameraModes
33 #include "collision.h"
34 #include "content_cso.h"
35 #include "environment.h"
37 #include "localplayer.h"
41 #include "serialization.h" // For decompressZlib
45 #include "wieldmesh.h"
48 #include "client/shader.h"
49 #include "client/minimap.h"
52 struct ToolCapabilities;
54 std::unordered_map<u16, ClientActiveObject::Factory> ClientActiveObject::m_types;
57 void SmoothTranslator<T>::init(T current)
60 val_current = current;
63 anim_time_counter = 0;
68 void SmoothTranslator<T>::update(T new_target, bool is_end_position, float update_interval)
70 aim_is_end = is_end_position;
71 val_old = val_current;
72 val_target = new_target;
73 if (update_interval > 0) {
74 anim_time = update_interval;
76 if (anim_time < 0.001 || anim_time > 1.0)
77 anim_time = anim_time_counter;
79 anim_time = anim_time * 0.9 + anim_time_counter * 0.1;
81 anim_time_counter = 0;
85 void SmoothTranslator<T>::translate(f32 dtime)
87 anim_time_counter = anim_time_counter + dtime;
88 T val_diff = val_target - val_old;
90 if (anim_time > 0.001)
91 moveratio = anim_time_counter / anim_time;
92 f32 move_end = aim_is_end ? 1.0 : 1.5;
94 // Move a bit less than should, to avoid oscillation
95 moveratio = std::min(moveratio * 0.8f, move_end);
96 val_current = val_old + val_diff * moveratio;
99 void SmoothTranslatorWrapped::translate(f32 dtime)
101 anim_time_counter = anim_time_counter + dtime;
102 f32 val_diff = std::abs(val_target - val_old);
103 if (val_diff > 180.f)
104 val_diff = 360.f - val_diff;
107 if (anim_time > 0.001)
108 moveratio = anim_time_counter / anim_time;
109 f32 move_end = aim_is_end ? 1.0 : 1.5;
111 // Move a bit less than should, to avoid oscillation
112 moveratio = std::min(moveratio * 0.8f, move_end);
113 wrappedApproachShortest(val_current, val_target,
114 val_diff * moveratio, 360.f);
117 void SmoothTranslatorWrappedv3f::translate(f32 dtime)
119 anim_time_counter = anim_time_counter + dtime;
122 val_diff_v3f.X = std::abs(val_target.X - val_old.X);
123 val_diff_v3f.Y = std::abs(val_target.Y - val_old.Y);
124 val_diff_v3f.Z = std::abs(val_target.Z - val_old.Z);
126 if (val_diff_v3f.X > 180.f)
127 val_diff_v3f.X = 360.f - val_diff_v3f.X;
129 if (val_diff_v3f.Y > 180.f)
130 val_diff_v3f.Y = 360.f - val_diff_v3f.Y;
132 if (val_diff_v3f.Z > 180.f)
133 val_diff_v3f.Z = 360.f - val_diff_v3f.Z;
136 if (anim_time > 0.001)
137 moveratio = anim_time_counter / anim_time;
138 f32 move_end = aim_is_end ? 1.0 : 1.5;
140 // Move a bit less than should, to avoid oscillation
141 moveratio = std::min(moveratio * 0.8f, move_end);
142 wrappedApproachShortest(val_current.X, val_target.X,
143 val_diff_v3f.X * moveratio, 360.f);
145 wrappedApproachShortest(val_current.Y, val_target.Y,
146 val_diff_v3f.Y * moveratio, 360.f);
148 wrappedApproachShortest(val_current.Z, val_target.Z,
149 val_diff_v3f.Z * moveratio, 360.f);
156 static void setBillboardTextureMatrix(scene::IBillboardSceneNode *bill,
157 float txs, float tys, int col, int row)
159 video::SMaterial& material = bill->getMaterial(0);
160 core::matrix4& matrix = material.getTextureMatrix(0);
161 matrix.setTextureTranslate(txs*col, tys*row);
162 matrix.setTextureScale(txs, tys);
165 // Evaluate transform chain recursively; irrlicht does not do this for us
166 static void updatePositionRecursive(scene::ISceneNode *node)
168 scene::ISceneNode *parent = node->getParent();
170 updatePositionRecursive(parent);
171 node->updateAbsolutePosition();
174 static bool logOnce(const std::ostringstream &from, std::ostream &log_to)
176 thread_local std::vector<u64> logged;
178 std::string message = from.str();
179 u64 hash = murmur_hash_64_ua(message.data(), message.length(), 0xBADBABE);
181 if (std::find(logged.begin(), logged.end(), hash) != logged.end())
183 logged.push_back(hash);
184 log_to << message << std::endl;
192 class TestCAO : public ClientActiveObject
195 TestCAO(Client *client, ClientEnvironment *env);
196 virtual ~TestCAO() = default;
198 ActiveObjectType getType() const
200 return ACTIVEOBJECT_TYPE_TEST;
203 static ClientActiveObject* create(Client *client, ClientEnvironment *env);
205 void addToScene(ITextureSource *tsrc, scene::ISceneManager *smgr);
206 void removeFromScene(bool permanent);
207 void updateLight(u32 day_night_ratio);
208 void updateNodePos();
210 void step(float dtime, ClientEnvironment *env);
212 void processMessage(const std::string &data);
214 bool getCollisionBox(aabb3f *toset) const { return false; }
216 scene::IMeshSceneNode *m_node;
221 TestCAO proto_TestCAO(NULL, NULL);
223 TestCAO::TestCAO(Client *client, ClientEnvironment *env):
224 ClientActiveObject(0, client, env),
226 m_position(v3f(0,10*BS,0))
228 ClientActiveObject::registerType(getType(), create);
231 ClientActiveObject* TestCAO::create(Client *client, ClientEnvironment *env)
233 return new TestCAO(client, env);
236 void TestCAO::addToScene(ITextureSource *tsrc, scene::ISceneManager *smgr)
241 //video::IVideoDriver* driver = smgr->getVideoDriver();
243 scene::SMesh *mesh = new scene::SMesh();
244 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
245 video::SColor c(255,255,255,255);
246 video::S3DVertex vertices[4] =
248 video::S3DVertex(-BS/2,-BS/4,0, 0,0,0, c, 0,1),
249 video::S3DVertex(BS/2,-BS/4,0, 0,0,0, c, 1,1),
250 video::S3DVertex(BS/2,BS/4,0, 0,0,0, c, 1,0),
251 video::S3DVertex(-BS/2,BS/4,0, 0,0,0, c, 0,0),
253 u16 indices[] = {0,1,2,2,3,0};
254 buf->append(vertices, 4, indices, 6);
256 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
257 buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
258 buf->getMaterial().setTexture(0, tsrc->getTextureForMesh("rat.png"));
259 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
260 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
261 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
263 mesh->addMeshBuffer(buf);
265 m_node = smgr->addMeshSceneNode(mesh, NULL);
270 void TestCAO::removeFromScene(bool permanent)
279 void TestCAO::updateLight(u32 day_night_ratio)
283 void TestCAO::updateNodePos()
288 m_node->setPosition(m_position);
289 //m_node->setRotation(v3f(0, 45, 0));
292 void TestCAO::step(float dtime, ClientEnvironment *env)
296 v3f rot = m_node->getRotation();
297 //infostream<<"dtime="<<dtime<<", rot.Y="<<rot.Y<<std::endl;
298 rot.Y += dtime * 180;
299 m_node->setRotation(rot);
303 void TestCAO::processMessage(const std::string &data)
305 infostream<<"TestCAO: Got data: "<<data<<std::endl;
306 std::istringstream is(data, std::ios::binary);
324 #include "clientobject.h"
326 GenericCAO::GenericCAO(Client *client, ClientEnvironment *env):
327 ClientActiveObject(0, client, env)
329 if (client == NULL) {
330 ClientActiveObject::registerType(getType(), create);
336 bool GenericCAO::getCollisionBox(aabb3f *toset) const
340 //update collision box
341 toset->MinEdge = m_prop.collisionbox.MinEdge * BS;
342 toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS;
344 toset->MinEdge += m_position;
345 toset->MaxEdge += m_position;
353 bool GenericCAO::collideWithObjects() const
355 return m_prop.collideWithObjects;
358 void GenericCAO::initialize(const std::string &data)
360 infostream<<"GenericCAO: Got init data"<<std::endl;
361 processInitData(data);
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);
386 // Check if it's the current player
387 LocalPlayer *player = m_env->getLocalPlayer();
388 if (player && strcmp(player->getName(), m_name.c_str()) == 0) {
389 m_is_local_player = true;
390 m_is_visible = false;
391 player->setCAO(this);
395 const u8 num_messages = readU8(is);
397 for (int i = 0; i < num_messages; i++) {
398 std::string message = deSerializeString32(is);
399 processMessage(message);
402 m_rotation = wrapDegrees_0_360_v3f(m_rotation);
403 pos_translator.init(m_position);
404 rot_translator.init(m_rotation);
408 GenericCAO::~GenericCAO()
410 removeFromScene(true);
413 bool GenericCAO::getSelectionBox(aabb3f *toset) const
415 if (!m_prop.is_visible || !m_is_visible || m_is_local_player
416 || !m_prop.pointable) {
419 *toset = m_selection_box;
423 const v3f GenericCAO::getPosition() const
426 return pos_translator.val_current;
428 // Calculate real position in world based on MatrixNode
430 v3s16 camera_offset = m_env->getCameraOffset();
431 return m_matrixnode->getAbsolutePosition() +
432 intToFloat(camera_offset, BS);
438 bool GenericCAO::isImmortal() const
440 return itemgroup_get(getGroups(), "immortal");
443 scene::ISceneNode *GenericCAO::getSceneNode() const
449 if (m_animated_meshnode) {
450 return m_animated_meshnode;
453 if (m_wield_meshnode) {
454 return m_wield_meshnode;
463 scene::IAnimatedMeshSceneNode *GenericCAO::getAnimatedMeshSceneNode() const
465 return m_animated_meshnode;
468 void GenericCAO::setChildrenVisible(bool toset)
470 for (u16 cao_id : m_attachment_child_ids) {
471 GenericCAO *obj = m_env->getGenericCAO(cao_id);
473 // Check if the entity is forced to appear in first person.
474 obj->setVisible(obj->m_force_visible ? true : toset);
479 void GenericCAO::setAttachment(int parent_id, const std::string &bone,
480 v3f position, v3f rotation, bool force_visible)
482 int old_parent = m_attachment_parent_id;
483 m_attachment_parent_id = parent_id;
484 m_attachment_bone = bone;
485 m_attachment_position = position;
486 m_attachment_rotation = rotation;
487 m_force_visible = force_visible;
489 ClientActiveObject *parent = m_env->getActiveObject(parent_id);
491 if (parent_id != old_parent) {
492 if (auto *o = m_env->getActiveObject(old_parent))
493 o->removeAttachmentChild(m_id);
495 parent->addAttachmentChild(m_id);
499 // Forcibly show attachments if required by set_attach
500 if (m_force_visible) {
502 } else if (!m_is_local_player) {
503 // Objects attached to the local player should be hidden in first person
504 m_is_visible = !m_attached_to_local ||
505 m_client->getCamera()->getCameraMode() != CAMERA_MODE_FIRST;
506 m_force_visible = false;
508 // Local players need to have this set,
509 // otherwise first person attachments fail.
514 void GenericCAO::getAttachment(int *parent_id, std::string *bone, v3f *position,
515 v3f *rotation, bool *force_visible) const
517 *parent_id = m_attachment_parent_id;
518 *bone = m_attachment_bone;
519 *position = m_attachment_position;
520 *rotation = m_attachment_rotation;
521 *force_visible = m_force_visible;
524 void GenericCAO::clearChildAttachments()
526 // Cannot use for-loop here: setAttachment() modifies 'm_attachment_child_ids'!
527 while (!m_attachment_child_ids.empty()) {
528 int child_id = *m_attachment_child_ids.begin();
530 if (ClientActiveObject *child = m_env->getActiveObject(child_id))
531 child->setAttachment(0, "", v3f(), v3f(), false);
533 removeAttachmentChild(child_id);
537 void GenericCAO::clearParentAttachment()
539 if (m_attachment_parent_id)
540 setAttachment(0, "", m_attachment_position, m_attachment_rotation, false);
542 setAttachment(0, "", v3f(), v3f(), false);
545 void GenericCAO::addAttachmentChild(int child_id)
547 m_attachment_child_ids.insert(child_id);
550 void GenericCAO::removeAttachmentChild(int child_id)
552 m_attachment_child_ids.erase(child_id);
555 ClientActiveObject* GenericCAO::getParent() const
557 return m_attachment_parent_id ? m_env->getActiveObject(m_attachment_parent_id) :
561 void GenericCAO::removeFromScene(bool permanent)
563 // Should be true when removing the object permanently
564 // and false when refreshing (eg: updating visuals)
565 if (m_env && permanent) {
566 // The client does not know whether this object does re-appear to
567 // a later time, thus do not clear child attachments.
569 clearParentAttachment();
572 if (auto shadow = RenderingEngine::get_shadow_renderer())
573 shadow->removeNodeFromShadowList(getSceneNode());
576 m_meshnode->remove();
578 m_meshnode = nullptr;
579 } else if (m_animated_meshnode) {
580 m_animated_meshnode->remove();
581 m_animated_meshnode->drop();
582 m_animated_meshnode = nullptr;
583 } else if (m_wield_meshnode) {
584 m_wield_meshnode->remove();
585 m_wield_meshnode->drop();
586 m_wield_meshnode = nullptr;
587 } else if (m_spritenode) {
588 m_spritenode->remove();
589 m_spritenode->drop();
590 m_spritenode = nullptr;
594 m_matrixnode->remove();
595 m_matrixnode->drop();
596 m_matrixnode = nullptr;
600 m_client->getCamera()->removeNametag(m_nametag);
604 if (m_marker && m_client->getMinimap())
605 m_client->getMinimap()->removeMarker(&m_marker);
608 void GenericCAO::addToScene(ITextureSource *tsrc, scene::ISceneManager *smgr)
612 if (getSceneNode() != NULL) {
616 m_visuals_expired = false;
618 if (!m_prop.is_visible)
621 infostream << "GenericCAO::addToScene(): " << m_prop.visual << std::endl;
623 if (m_enable_shaders) {
624 IShaderSource *shader_source = m_client->getShaderSource();
625 MaterialType material_type;
627 if (m_prop.shaded && m_prop.glow == 0)
628 material_type = (m_prop.use_texture_alpha) ?
629 TILE_MATERIAL_ALPHA : TILE_MATERIAL_BASIC;
631 material_type = (m_prop.use_texture_alpha) ?
632 TILE_MATERIAL_PLAIN_ALPHA : TILE_MATERIAL_PLAIN;
634 u32 shader_id = shader_source->getShader("object_shader", material_type, NDT_NORMAL);
635 m_material_type = shader_source->getShaderInfo(shader_id).material;
637 m_material_type = (m_prop.use_texture_alpha) ?
638 video::EMT_TRANSPARENT_ALPHA_CHANNEL : video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
641 auto grabMatrixNode = [this] {
642 m_matrixnode = m_smgr->addDummyTransformationSceneNode();
643 m_matrixnode->grab();
646 auto setSceneNodeMaterial = [this] (scene::ISceneNode *node) {
647 node->setMaterialFlag(video::EMF_LIGHTING, false);
648 node->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
649 node->setMaterialFlag(video::EMF_FOG_ENABLE, true);
650 node->setMaterialType(m_material_type);
652 if (m_enable_shaders) {
653 node->setMaterialFlag(video::EMF_GOURAUD_SHADING, false);
654 node->setMaterialFlag(video::EMF_NORMALIZE_NORMALS, true);
658 if (m_prop.visual == "sprite") {
660 m_spritenode = m_smgr->addBillboardSceneNode(
661 m_matrixnode, v2f(1, 1), v3f(0,0,0), -1);
662 m_spritenode->grab();
663 m_spritenode->setMaterialTexture(0,
664 tsrc->getTextureForMesh("no_texture.png"));
666 setSceneNodeMaterial(m_spritenode);
668 m_spritenode->setSize(v2f(m_prop.visual_size.X,
669 m_prop.visual_size.Y) * BS);
671 const float txs = 1.0 / 1;
672 const float tys = 1.0 / 1;
673 setBillboardTextureMatrix(m_spritenode,
676 } else if (m_prop.visual == "upright_sprite") {
678 scene::SMesh *mesh = new scene::SMesh();
679 double dx = BS * m_prop.visual_size.X / 2;
680 double dy = BS * m_prop.visual_size.Y / 2;
681 video::SColor c(0xFFFFFFFF);
684 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
685 video::S3DVertex vertices[4] = {
686 video::S3DVertex(-dx, -dy, 0, 0,0,1, c, 1,1),
687 video::S3DVertex( dx, -dy, 0, 0,0,1, c, 0,1),
688 video::S3DVertex( dx, dy, 0, 0,0,1, c, 0,0),
689 video::S3DVertex(-dx, dy, 0, 0,0,1, c, 1,0),
692 // Move minimal Y position to 0 (feet position)
693 for (video::S3DVertex &vertex : vertices)
696 u16 indices[] = {0,1,2,2,3,0};
697 buf->append(vertices, 4, indices, 6);
699 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
700 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
701 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
702 buf->getMaterial().MaterialType = m_material_type;
704 if (m_enable_shaders) {
705 buf->getMaterial().EmissiveColor = c;
706 buf->getMaterial().setFlag(video::EMF_GOURAUD_SHADING, false);
707 buf->getMaterial().setFlag(video::EMF_NORMALIZE_NORMALS, true);
711 mesh->addMeshBuffer(buf);
715 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
716 video::S3DVertex vertices[4] = {
717 video::S3DVertex( dx,-dy, 0, 0,0,-1, c, 1,1),
718 video::S3DVertex(-dx,-dy, 0, 0,0,-1, c, 0,1),
719 video::S3DVertex(-dx, dy, 0, 0,0,-1, c, 0,0),
720 video::S3DVertex( dx, dy, 0, 0,0,-1, c, 1,0),
723 // Move minimal Y position to 0 (feet position)
724 for (video::S3DVertex &vertex : vertices)
727 u16 indices[] = {0,1,2,2,3,0};
728 buf->append(vertices, 4, indices, 6);
730 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
731 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
732 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
733 buf->getMaterial().MaterialType = m_material_type;
735 if (m_enable_shaders) {
736 buf->getMaterial().EmissiveColor = c;
737 buf->getMaterial().setFlag(video::EMF_GOURAUD_SHADING, false);
738 buf->getMaterial().setFlag(video::EMF_NORMALIZE_NORMALS, true);
742 mesh->addMeshBuffer(buf);
745 m_meshnode = m_smgr->addMeshSceneNode(mesh, m_matrixnode);
748 } else if (m_prop.visual == "cube") {
750 scene::IMesh *mesh = createCubeMesh(v3f(BS,BS,BS));
751 m_meshnode = m_smgr->addMeshSceneNode(mesh, m_matrixnode);
755 m_meshnode->setScale(m_prop.visual_size);
756 m_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
757 m_prop.backface_culling);
759 setSceneNodeMaterial(m_meshnode);
760 } else if (m_prop.visual == "mesh") {
762 scene::IAnimatedMesh *mesh = m_client->getMesh(m_prop.mesh, true);
764 if (!checkMeshNormals(mesh)) {
765 infostream << "GenericCAO: recalculating normals for mesh "
766 << m_prop.mesh << std::endl;
767 m_smgr->getMeshManipulator()->
768 recalculateNormals(mesh, true, false);
771 m_animated_meshnode = m_smgr->addAnimatedMeshSceneNode(mesh, m_matrixnode);
772 m_animated_meshnode->grab();
773 mesh->drop(); // The scene node took hold of it
774 m_animated_meshnode->animateJoints(); // Needed for some animations
775 m_animated_meshnode->setScale(m_prop.visual_size);
777 // set vertex colors to ensure alpha is set
778 setMeshColor(m_animated_meshnode->getMesh(), video::SColor(0xFFFFFFFF));
780 setAnimatedMeshColor(m_animated_meshnode, video::SColor(0xFFFFFFFF));
782 setSceneNodeMaterial(m_animated_meshnode);
784 m_animated_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
785 m_prop.backface_culling);
787 errorstream<<"GenericCAO::addToScene(): Could not load mesh "<<m_prop.mesh<<std::endl;
788 } else if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
791 if (m_prop.wield_item.empty()) {
792 // Old format, only textures are specified.
793 infostream << "textures: " << m_prop.textures.size() << std::endl;
794 if (!m_prop.textures.empty()) {
795 infostream << "textures[0]: " << m_prop.textures[0]
797 IItemDefManager *idef = m_client->idef();
798 item = ItemStack(m_prop.textures[0], 1, 0, idef);
801 infostream << "serialized form: " << m_prop.wield_item << std::endl;
802 item.deSerialize(m_prop.wield_item, m_client->idef());
804 m_wield_meshnode = new WieldMeshSceneNode(m_smgr, -1);
805 m_wield_meshnode->setItem(item, m_client,
806 (m_prop.visual == "wielditem"));
808 m_wield_meshnode->setScale(m_prop.visual_size / 2.0f);
809 m_wield_meshnode->setColor(video::SColor(0xFFFFFFFF));
811 infostream<<"GenericCAO::addToScene(): \""<<m_prop.visual
812 <<"\" not supported"<<std::endl;
815 /* don't update while punch texture modifier is active */
816 if (m_reset_textures_timer < 0)
817 updateTextures(m_current_texture_modifier);
819 if (scene::ISceneNode *node = getSceneNode()) {
821 node->setParent(m_matrixnode);
823 if (auto shadow = RenderingEngine::get_shadow_renderer())
824 shadow->addNodeToShadowList(node);
831 updateBonePosition();
833 setNodeLight(m_last_light);
836 if (m_animated_meshnode) {
837 u32 mat_count = m_animated_meshnode->getMaterialCount();
838 if (mat_count == 0 || m_prop.textures.empty()) {
840 } else if (mat_count > m_prop.textures.size()) {
841 std::ostringstream oss;
842 oss << "GenericCAO::addToScene(): Model "
843 << m_prop.mesh << " loaded with " << mat_count
844 << " mesh buffers but only " << m_prop.textures.size()
845 << " texture(s) specifed, this is deprecated.";
846 logOnce(oss, warningstream);
848 video::ITexture *last = m_animated_meshnode->getMaterial(0).TextureLayer[0].Texture;
849 for (u32 i = 1; i < mat_count; i++) {
850 auto &layer = m_animated_meshnode->getMaterial(i).TextureLayer[0];
852 layer.Texture = last;
853 last = layer.Texture;
859 void GenericCAO::updateLight(u32 day_night_ratio)
864 u16 light_at_pos = 0;
865 u8 light_at_pos_intensity = 0;
869 u16 npos = getLightPosition(pos);
870 for (u16 i = 0; i < npos; i++) {
872 MapNode n = m_env->getMap().getNode(pos[i], &this_ok);
874 u16 this_light = getInteriorLight(n, 0, m_client->ndef());
875 u8 this_light_intensity = MYMAX(this_light & 0xFF, (this_light >> 8) && 0xFF);
876 if (this_light_intensity > light_at_pos_intensity) {
877 light_at_pos = this_light;
878 light_at_pos_intensity = this_light_intensity;
884 light_at_pos = LIGHT_SUN;
886 video::SColor light = encode_light(light_at_pos, m_glow);
887 if (!m_enable_shaders)
888 final_color_blend(&light, light_at_pos, day_night_ratio);
890 if (light != m_last_light) {
891 m_last_light = light;
896 void GenericCAO::setNodeLight(const video::SColor &light_color)
898 if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
899 if (m_wield_meshnode)
900 m_wield_meshnode->setNodeLightColor(light_color);
904 if (m_enable_shaders) {
905 if (m_prop.visual == "upright_sprite") {
909 scene::IMesh *mesh = m_meshnode->getMesh();
910 for (u32 i = 0; i < mesh->getMeshBufferCount(); ++i) {
911 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
912 buf->getMaterial().EmissiveColor = light_color;
915 scene::ISceneNode *node = getSceneNode();
919 for (u32 i = 0; i < node->getMaterialCount(); ++i) {
920 video::SMaterial &material = node->getMaterial(i);
921 material.EmissiveColor = light_color;
926 setMeshColor(m_meshnode->getMesh(), light_color);
927 } else if (m_animated_meshnode) {
928 setAnimatedMeshColor(m_animated_meshnode, light_color);
929 } else if (m_spritenode) {
930 m_spritenode->setColor(light_color);
935 u16 GenericCAO::getLightPosition(v3s16 *pos)
937 const auto &box = m_prop.collisionbox;
938 pos[0] = floatToInt(m_position + box.MinEdge * BS, BS);
939 pos[1] = floatToInt(m_position + box.MaxEdge * BS, BS);
941 // Skip center pos if it falls into the same node as Min or MaxEdge
942 if ((box.MaxEdge - box.MinEdge).getLengthSQ() < 3.0f)
944 pos[2] = floatToInt(m_position + box.getCenter() * BS, BS);
948 void GenericCAO::updateMarker()
950 if (!m_client->getMinimap())
953 if (!m_prop.show_on_minimap) {
955 m_client->getMinimap()->removeMarker(&m_marker);
962 scene::ISceneNode *node = getSceneNode();
965 m_marker = m_client->getMinimap()->addMarker(node);
968 void GenericCAO::updateNametag()
970 if (m_is_local_player) // No nametag for local player
973 if (m_prop.nametag.empty() || m_prop.nametag_color.getAlpha() == 0) {
976 m_client->getCamera()->removeNametag(m_nametag);
982 scene::ISceneNode *node = getSceneNode();
987 pos.Y = m_prop.selectionbox.MaxEdge.Y + 0.3f;
990 m_nametag = m_client->getCamera()->addNametag(node,
991 m_prop.nametag, m_prop.nametag_color,
992 m_prop.nametag_bgcolor, pos);
995 m_nametag->text = m_prop.nametag;
996 m_nametag->textcolor = m_prop.nametag_color;
997 m_nametag->bgcolor = m_prop.nametag_bgcolor;
998 m_nametag->pos = pos;
1002 void GenericCAO::updateNodePos()
1004 if (getParent() != NULL)
1007 scene::ISceneNode *node = getSceneNode();
1010 v3s16 camera_offset = m_env->getCameraOffset();
1011 v3f pos = pos_translator.val_current -
1012 intToFloat(camera_offset, BS);
1013 getPosRotMatrix().setTranslation(pos);
1014 if (node != m_spritenode) { // rotate if not a sprite
1015 v3f rot = m_is_local_player ? -m_rotation : -rot_translator.val_current;
1016 setPitchYawRoll(getPosRotMatrix(), rot);
1021 void GenericCAO::step(float dtime, ClientEnvironment *env)
1023 // Handle model animations and update positions instantly to prevent lags
1024 if (m_is_local_player) {
1025 LocalPlayer *player = m_env->getLocalPlayer();
1026 m_position = player->getPosition();
1027 pos_translator.val_current = m_position;
1028 m_rotation.Y = wrapDegrees_0_360(player->getYaw());
1029 rot_translator.val_current = m_rotation;
1032 int old_anim = player->last_animation;
1033 float old_anim_speed = player->last_animation_speed;
1034 m_velocity = v3f(0,0,0);
1035 m_acceleration = v3f(0,0,0);
1036 const PlayerControl &controls = player->getPlayerControl();
1037 f32 new_speed = player->local_animation_speed;
1039 bool walking = false;
1040 if (controls.movement_speed > 0.001f) {
1041 new_speed *= controls.movement_speed;
1045 v2s32 new_anim = v2s32(0,0);
1046 bool allow_update = false;
1048 // increase speed if using fast or flying fast
1049 if((g_settings->getBool("fast_move") &&
1050 m_client->checkLocalPrivilege("fast")) &&
1052 (!player->touching_ground &&
1053 g_settings->getBool("free_move") &&
1054 m_client->checkLocalPrivilege("fly"))))
1056 // slowdown speed if sneaking
1057 if (controls.sneak && walking)
1060 if (walking && (controls.dig || controls.place)) {
1061 new_anim = player->local_animations[3];
1062 player->last_animation = WD_ANIM;
1063 } else if (walking) {
1064 new_anim = player->local_animations[1];
1065 player->last_animation = WALK_ANIM;
1066 } else if (controls.dig || controls.place) {
1067 new_anim = player->local_animations[2];
1068 player->last_animation = DIG_ANIM;
1071 // Apply animations if input detected and not attached
1072 // or set idle animation
1073 if ((new_anim.X + new_anim.Y) > 0 && !getParent()) {
1074 allow_update = true;
1075 m_animation_range = new_anim;
1076 m_animation_speed = new_speed;
1077 player->last_animation_speed = m_animation_speed;
1079 player->last_animation = NO_ANIM;
1081 if (old_anim != NO_ANIM) {
1082 m_animation_range = player->local_animations[0];
1087 // Update local player animations
1088 if ((player->last_animation != old_anim ||
1089 m_animation_speed != old_anim_speed) &&
1090 player->last_animation != NO_ANIM && allow_update)
1096 if (m_visuals_expired && m_smgr) {
1097 m_visuals_expired = false;
1099 // Attachments, part 1: All attached objects must be unparented first,
1100 // or Irrlicht causes a segmentation fault
1101 for (u16 cao_id : m_attachment_child_ids) {
1102 ClientActiveObject *obj = m_env->getActiveObject(cao_id);
1104 scene::ISceneNode *child_node = obj->getSceneNode();
1105 // The node's parent is always an IDummyTraformationSceneNode,
1106 // so we need to reparent that one instead.
1108 child_node->getParent()->setParent(m_smgr->getRootSceneNode());
1112 removeFromScene(false);
1113 addToScene(m_client->tsrc(), m_smgr);
1115 // Attachments, part 2: Now that the parent has been refreshed, put its attachments back
1116 for (u16 cao_id : m_attachment_child_ids) {
1117 ClientActiveObject *obj = m_env->getActiveObject(cao_id);
1119 obj->updateAttachments();
1123 // Make sure m_is_visible is always applied
1124 scene::ISceneNode *node = getSceneNode();
1126 node->setVisible(m_is_visible);
1128 if(getParent() != NULL) // Attachments should be glued to their parent by Irrlicht
1130 // Set these for later
1131 m_position = getPosition();
1132 m_velocity = v3f(0,0,0);
1133 m_acceleration = v3f(0,0,0);
1134 pos_translator.val_current = m_position;
1135 pos_translator.val_target = m_position;
1137 rot_translator.translate(dtime);
1138 v3f lastpos = pos_translator.val_current;
1142 aabb3f box = m_prop.collisionbox;
1145 collisionMoveResult moveresult;
1146 f32 pos_max_d = BS*0.125; // Distance per iteration
1147 v3f p_pos = m_position;
1148 v3f p_velocity = m_velocity;
1149 moveresult = collisionMoveSimple(env,env->getGameDef(),
1150 pos_max_d, box, m_prop.stepheight, dtime,
1151 &p_pos, &p_velocity, m_acceleration,
1152 this, m_prop.collideWithObjects);
1155 m_velocity = p_velocity;
1157 bool is_end_position = moveresult.collides;
1158 pos_translator.update(m_position, is_end_position, dtime);
1160 m_position += dtime * m_velocity + 0.5 * dtime * dtime * m_acceleration;
1161 m_velocity += dtime * m_acceleration;
1162 pos_translator.update(m_position, pos_translator.aim_is_end,
1163 pos_translator.anim_time);
1165 pos_translator.translate(dtime);
1168 float moved = lastpos.getDistanceFrom(pos_translator.val_current);
1169 m_step_distance_counter += moved;
1170 if (m_step_distance_counter > 1.5f * BS) {
1171 m_step_distance_counter = 0.0f;
1172 if (!m_is_local_player && m_prop.makes_footstep_sound) {
1173 const NodeDefManager *ndef = m_client->ndef();
1174 v3s16 p = floatToInt(getPosition() +
1175 v3f(0.0f, (m_prop.collisionbox.MinEdge.Y - 0.5f) * BS, 0.0f), BS);
1176 MapNode n = m_env->getMap().getNode(p);
1177 SimpleSoundSpec spec = ndef->get(n).sound_footstep;
1178 // Reduce footstep gain, as non-local-player footsteps are
1181 m_client->sound()->playSoundAt(spec, false, getPosition());
1186 m_anim_timer += dtime;
1187 if(m_anim_timer >= m_anim_framelength)
1189 m_anim_timer -= m_anim_framelength;
1191 if(m_anim_frame >= m_anim_num_frames)
1197 if(m_reset_textures_timer >= 0)
1199 m_reset_textures_timer -= dtime;
1200 if(m_reset_textures_timer <= 0) {
1201 m_reset_textures_timer = -1;
1202 updateTextures(m_previous_texture_modifier);
1206 if (!getParent() && node && fabs(m_prop.automatic_rotate) > 0.001f) {
1207 // This is the child node's rotation. It is only used for automatic_rotate.
1208 v3f local_rot = node->getRotation();
1209 local_rot.Y = modulo360f(local_rot.Y - dtime * core::RADTODEG *
1210 m_prop.automatic_rotate);
1211 node->setRotation(local_rot);
1214 if (!getParent() && m_prop.automatic_face_movement_dir &&
1215 (fabs(m_velocity.Z) > 0.001f || fabs(m_velocity.X) > 0.001f)) {
1216 float target_yaw = atan2(m_velocity.Z, m_velocity.X) * 180 / M_PI
1217 + m_prop.automatic_face_movement_dir_offset;
1218 float max_rotation_per_sec =
1219 m_prop.automatic_face_movement_max_rotation_per_sec;
1221 if (max_rotation_per_sec > 0) {
1222 wrappedApproachShortest(m_rotation.Y, target_yaw,
1223 dtime * max_rotation_per_sec, 360.f);
1225 // Negative values of max_rotation_per_sec mean disabled.
1226 m_rotation.Y = target_yaw;
1229 rot_translator.val_current = m_rotation;
1233 if (m_animated_meshnode) {
1234 // Everything must be updated; the whole transform
1235 // chain as well as the animated mesh node.
1236 // Otherwise, bone attachments would be relative to
1237 // a position that's one frame old.
1239 updatePositionRecursive(m_matrixnode);
1240 m_animated_meshnode->updateAbsolutePosition();
1241 m_animated_meshnode->animateJoints();
1242 updateBonePosition();
1246 void GenericCAO::updateTexturePos()
1250 scene::ICameraSceneNode* camera =
1251 m_spritenode->getSceneManager()->getActiveCamera();
1254 v3f cam_to_entity = m_spritenode->getAbsolutePosition()
1255 - camera->getAbsolutePosition();
1256 cam_to_entity.normalize();
1258 int row = m_tx_basepos.Y;
1259 int col = m_tx_basepos.X;
1261 // Yawpitch goes rightwards
1262 if (m_tx_select_horiz_by_yawpitch) {
1263 if (cam_to_entity.Y > 0.75)
1265 else if (cam_to_entity.Y < -0.75)
1269 atan2(cam_to_entity.Z, cam_to_entity.X) / M_PI * 180.;
1270 float dir = mob_dir - m_rotation.Y;
1271 dir = wrapDegrees_180(dir);
1272 if (std::fabs(wrapDegrees_180(dir - 0)) <= 45.1f)
1274 else if(std::fabs(wrapDegrees_180(dir - 90)) <= 45.1f)
1276 else if(std::fabs(wrapDegrees_180(dir - 180)) <= 45.1f)
1278 else if(std::fabs(wrapDegrees_180(dir + 90)) <= 45.1f)
1285 // Animation goes downwards
1286 row += m_anim_frame;
1288 float txs = m_tx_size.X;
1289 float tys = m_tx_size.Y;
1290 setBillboardTextureMatrix(m_spritenode, txs, tys, col, row);
1293 else if (m_meshnode) {
1294 if (m_prop.visual == "upright_sprite") {
1295 int row = m_tx_basepos.Y;
1296 int col = m_tx_basepos.X;
1298 // Animation goes downwards
1299 row += m_anim_frame;
1301 const auto &tx = m_tx_size;
1302 v2f t[4] = { // cf. vertices in GenericCAO::addToScene()
1303 tx * v2f(col+1, row+1),
1304 tx * v2f(col, row+1),
1306 tx * v2f(col+1, row),
1308 auto mesh = m_meshnode->getMesh();
1309 setMeshBufferTextureCoords(mesh->getMeshBuffer(0), t, 4);
1310 setMeshBufferTextureCoords(mesh->getMeshBuffer(1), t, 4);
1315 // Do not pass by reference, see header.
1316 void GenericCAO::updateTextures(std::string mod)
1318 ITextureSource *tsrc = m_client->tsrc();
1320 bool use_trilinear_filter = g_settings->getBool("trilinear_filter");
1321 bool use_bilinear_filter = g_settings->getBool("bilinear_filter");
1322 bool use_anisotropic_filter = g_settings->getBool("anisotropic_filter");
1324 m_previous_texture_modifier = m_current_texture_modifier;
1325 m_current_texture_modifier = mod;
1326 m_glow = m_prop.glow;
1328 video::ITexture *shadow_texture = nullptr;
1329 if (auto shadow = RenderingEngine::get_shadow_renderer())
1330 shadow_texture = shadow->get_texture();
1332 const u32 TEXTURE_LAYER_SHADOW = 3;
1335 if (m_prop.visual == "sprite") {
1336 std::string texturestring = "no_texture.png";
1337 if (!m_prop.textures.empty())
1338 texturestring = m_prop.textures[0];
1339 texturestring += mod;
1340 m_spritenode->getMaterial(0).MaterialType = m_material_type;
1341 m_spritenode->getMaterial(0).MaterialTypeParam = 0.5f;
1342 m_spritenode->setMaterialTexture(0,
1343 tsrc->getTextureForMesh(texturestring));
1344 m_spritenode->setMaterialTexture(TEXTURE_LAYER_SHADOW, shadow_texture);
1346 // This allows setting per-material colors. However, until a real lighting
1347 // system is added, the code below will have no effect. Once MineTest
1348 // has directional lighting, it should work automatically.
1349 if (!m_prop.colors.empty()) {
1350 m_spritenode->getMaterial(0).AmbientColor = m_prop.colors[0];
1351 m_spritenode->getMaterial(0).DiffuseColor = m_prop.colors[0];
1352 m_spritenode->getMaterial(0).SpecularColor = m_prop.colors[0];
1355 m_spritenode->getMaterial(0).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1356 m_spritenode->getMaterial(0).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1357 m_spritenode->getMaterial(0).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1361 else if (m_animated_meshnode) {
1362 if (m_prop.visual == "mesh") {
1363 for (u32 i = 0; i < m_prop.textures.size() &&
1364 i < m_animated_meshnode->getMaterialCount(); ++i) {
1365 std::string texturestring = m_prop.textures[i];
1366 if (texturestring.empty())
1367 continue; // Empty texture string means don't modify that material
1368 texturestring += mod;
1369 video::ITexture* texture = tsrc->getTextureForMesh(texturestring);
1371 errorstream<<"GenericCAO::updateTextures(): Could not load texture "<<texturestring<<std::endl;
1375 // Set material flags and texture
1376 video::SMaterial& material = m_animated_meshnode->getMaterial(i);
1377 material.MaterialType = m_material_type;
1378 material.MaterialTypeParam = 0.5f;
1379 material.TextureLayer[0].Texture = texture;
1380 material.TextureLayer[TEXTURE_LAYER_SHADOW].Texture = shadow_texture;
1381 material.setFlag(video::EMF_LIGHTING, true);
1382 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1383 material.setFlag(video::EMF_BACK_FACE_CULLING, m_prop.backface_culling);
1385 // don't filter low-res textures, makes them look blurry
1386 // player models have a res of 64
1387 const core::dimension2d<u32> &size = texture->getOriginalSize();
1388 const u32 res = std::min(size.Height, size.Width);
1389 use_trilinear_filter &= res > 64;
1390 use_bilinear_filter &= res > 64;
1392 m_animated_meshnode->getMaterial(i)
1393 .setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1394 m_animated_meshnode->getMaterial(i)
1395 .setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1396 m_animated_meshnode->getMaterial(i)
1397 .setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1399 for (u32 i = 0; i < m_prop.colors.size() &&
1400 i < m_animated_meshnode->getMaterialCount(); ++i)
1402 // This allows setting per-material colors. However, until a real lighting
1403 // system is added, the code below will have no effect. Once MineTest
1404 // has directional lighting, it should work automatically.
1405 m_animated_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1406 m_animated_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1407 m_animated_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1412 else if (m_meshnode) {
1413 if(m_prop.visual == "cube")
1415 for (u32 i = 0; i < 6; ++i)
1417 std::string texturestring = "no_texture.png";
1418 if(m_prop.textures.size() > i)
1419 texturestring = m_prop.textures[i];
1420 texturestring += mod;
1423 // Set material flags and texture
1424 video::SMaterial& material = m_meshnode->getMaterial(i);
1425 material.MaterialType = m_material_type;
1426 material.MaterialTypeParam = 0.5f;
1427 material.setFlag(video::EMF_LIGHTING, false);
1428 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1429 material.setTexture(0,
1430 tsrc->getTextureForMesh(texturestring));
1431 material.setTexture(TEXTURE_LAYER_SHADOW, shadow_texture);
1432 material.getTextureMatrix(0).makeIdentity();
1434 // This allows setting per-material colors. However, until a real lighting
1435 // system is added, the code below will have no effect. Once MineTest
1436 // has directional lighting, it should work automatically.
1437 if(m_prop.colors.size() > i)
1439 m_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1440 m_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1441 m_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1444 m_meshnode->getMaterial(i).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1445 m_meshnode->getMaterial(i).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1446 m_meshnode->getMaterial(i).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1448 } else if (m_prop.visual == "upright_sprite") {
1449 scene::IMesh *mesh = m_meshnode->getMesh();
1451 std::string tname = "no_texture.png";
1452 if (!m_prop.textures.empty())
1453 tname = m_prop.textures[0];
1455 auto& material = m_meshnode->getMaterial(0);
1456 material.setTexture(0,
1457 tsrc->getTextureForMesh(tname));
1458 material.setTexture(TEXTURE_LAYER_SHADOW, shadow_texture);
1460 // This allows setting per-material colors. However, until a real lighting
1461 // system is added, the code below will have no effect. Once MineTest
1462 // has directional lighting, it should work automatically.
1463 if(!m_prop.colors.empty()) {
1464 material.AmbientColor = m_prop.colors[0];
1465 material.DiffuseColor = m_prop.colors[0];
1466 material.SpecularColor = m_prop.colors[0];
1469 material.setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1470 material.setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1471 material.setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1474 std::string tname = "no_texture.png";
1475 if (m_prop.textures.size() >= 2)
1476 tname = m_prop.textures[1];
1477 else if (!m_prop.textures.empty())
1478 tname = m_prop.textures[0];
1480 auto& material = m_meshnode->getMaterial(1);
1481 material.setTexture(0,
1482 tsrc->getTextureForMesh(tname));
1483 material.setTexture(TEXTURE_LAYER_SHADOW, shadow_texture);
1485 // This allows setting per-material colors. However, until a real lighting
1486 // system is added, the code below will have no effect. Once MineTest
1487 // has directional lighting, it should work automatically.
1488 if (m_prop.colors.size() >= 2) {
1489 material.AmbientColor = m_prop.colors[1];
1490 material.DiffuseColor = m_prop.colors[1];
1491 material.SpecularColor = m_prop.colors[1];
1492 } else if (!m_prop.colors.empty()) {
1493 material.AmbientColor = m_prop.colors[0];
1494 material.DiffuseColor = m_prop.colors[0];
1495 material.SpecularColor = m_prop.colors[0];
1498 material.setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1499 material.setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1500 material.setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1502 // Set mesh color (only if lighting is disabled)
1503 if (!m_prop.colors.empty() && m_glow < 0)
1504 setMeshColor(mesh, m_prop.colors[0]);
1507 // Prevent showing the player after changing texture
1508 if (m_is_local_player)
1509 updateMeshCulling();
1512 void GenericCAO::updateAnimation()
1514 if (!m_animated_meshnode)
1517 if (m_animated_meshnode->getStartFrame() != m_animation_range.X ||
1518 m_animated_meshnode->getEndFrame() != m_animation_range.Y)
1519 m_animated_meshnode->setFrameLoop(m_animation_range.X, m_animation_range.Y);
1520 if (m_animated_meshnode->getAnimationSpeed() != m_animation_speed)
1521 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1522 m_animated_meshnode->setTransitionTime(m_animation_blend);
1523 if (m_animated_meshnode->getLoopMode() != m_animation_loop)
1524 m_animated_meshnode->setLoopMode(m_animation_loop);
1527 void GenericCAO::updateAnimationSpeed()
1529 if (!m_animated_meshnode)
1532 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1535 void GenericCAO::updateBonePosition()
1537 if (m_bone_position.empty() || !m_animated_meshnode)
1540 m_animated_meshnode->setJointMode(scene::EJUOR_CONTROL); // To write positions to the mesh on render
1541 for (auto &it : m_bone_position) {
1542 std::string bone_name = it.first;
1543 scene::IBoneSceneNode* bone = m_animated_meshnode->getJointNode(bone_name.c_str());
1545 bone->setPosition(it.second.X);
1546 bone->setRotation(it.second.Y);
1550 // search through bones to find mistakenly rotated bones due to bug in Irrlicht
1551 for (u32 i = 0; i < m_animated_meshnode->getJointCount(); ++i) {
1552 scene::IBoneSceneNode *bone = m_animated_meshnode->getJointNode(i);
1556 //If bone is manually positioned there is no need to perform the bug check
1558 for (auto &it : m_bone_position) {
1559 if (it.first == bone->getName()) {
1567 // Workaround for Irrlicht bug
1568 // We check each bone to see if it has been rotated ~180deg from its expected position due to a bug in Irricht
1569 // when using EJUOR_CONTROL joint control. If the bug is detected we update the bone to the proper position
1570 // and update the bones transformation.
1571 v3f bone_rot = bone->getRelativeTransformation().getRotationDegrees();
1572 float offset = fabsf(bone_rot.X - bone->getRotation().X);
1573 if (offset > 179.9f && offset < 180.1f) {
1574 bone->setRotation(bone_rot);
1575 bone->updateAbsolutePosition();
1578 // The following is needed for set_bone_pos to propagate to
1579 // attached objects correctly.
1580 // Irrlicht ought to do this, but doesn't when using EJUOR_CONTROL.
1581 for (u32 i = 0; i < m_animated_meshnode->getJointCount(); ++i) {
1582 auto bone = m_animated_meshnode->getJointNode(i);
1583 // Look for the root bone.
1584 if (bone && bone->getParent() == m_animated_meshnode) {
1585 // Update entire skeleton.
1586 bone->updateAbsolutePositionOfAllChildren();
1592 void GenericCAO::updateAttachments()
1594 ClientActiveObject *parent = getParent();
1596 m_attached_to_local = parent && parent->isLocalPlayer();
1599 Following cases exist:
1600 m_attachment_parent_id == 0 && !parent
1601 This object is not attached
1602 m_attachment_parent_id != 0 && parent
1603 This object is attached
1604 m_attachment_parent_id != 0 && !parent
1605 This object will be attached as soon the parent is known
1606 m_attachment_parent_id == 0 && parent
1610 if (!parent) { // Detach or don't attach
1612 v3s16 camera_offset = m_env->getCameraOffset();
1613 v3f old_pos = getPosition();
1615 m_matrixnode->setParent(m_smgr->getRootSceneNode());
1616 getPosRotMatrix().setTranslation(old_pos - intToFloat(camera_offset, BS));
1617 m_matrixnode->updateAbsolutePosition();
1622 parent->updateAttachments();
1623 scene::ISceneNode *parent_node = parent->getSceneNode();
1624 scene::IAnimatedMeshSceneNode *parent_animated_mesh_node =
1625 parent->getAnimatedMeshSceneNode();
1626 if (parent_animated_mesh_node && !m_attachment_bone.empty()) {
1627 parent_node = parent_animated_mesh_node->getJointNode(m_attachment_bone.c_str());
1630 if (m_matrixnode && parent_node) {
1631 m_matrixnode->setParent(parent_node);
1632 parent_node->updateAbsolutePosition();
1633 getPosRotMatrix().setTranslation(m_attachment_position);
1634 //setPitchYawRoll(getPosRotMatrix(), m_attachment_rotation);
1635 // use Irrlicht eulers instead
1636 getPosRotMatrix().setRotationDegrees(m_attachment_rotation);
1637 m_matrixnode->updateAbsolutePosition();
1642 bool GenericCAO::visualExpiryRequired(const ObjectProperties &new_) const
1644 const ObjectProperties &old = m_prop;
1645 /* Visuals do not need to be expired for:
1646 * - nametag props: handled by updateNametag()
1647 * - textures: handled by updateTextures()
1648 * - sprite props: handled by updateTexturePos()
1649 * - glow: handled by updateLight()
1650 * - any other properties that do not change appearance
1653 bool uses_legacy_texture = new_.wield_item.empty() &&
1654 (new_.visual == "wielditem" || new_.visual == "item");
1655 // Ordered to compare primitive types before std::vectors
1656 return old.backface_culling != new_.backface_culling ||
1657 old.is_visible != new_.is_visible ||
1658 old.mesh != new_.mesh ||
1659 old.shaded != new_.shaded ||
1660 old.use_texture_alpha != new_.use_texture_alpha ||
1661 old.visual != new_.visual ||
1662 old.visual_size != new_.visual_size ||
1663 old.wield_item != new_.wield_item ||
1664 old.colors != new_.colors ||
1665 (uses_legacy_texture && old.textures != new_.textures);
1668 void GenericCAO::processMessage(const std::string &data)
1670 //infostream<<"GenericCAO: Got message"<<std::endl;
1671 std::istringstream is(data, std::ios::binary);
1673 u8 cmd = readU8(is);
1674 if (cmd == AO_CMD_SET_PROPERTIES) {
1675 ObjectProperties newprops;
1676 newprops.show_on_minimap = m_is_player; // default
1678 newprops.deSerialize(is);
1680 // Check what exactly changed
1681 bool expire_visuals = visualExpiryRequired(newprops);
1682 bool textures_changed = m_prop.textures != newprops.textures;
1685 m_prop = std::move(newprops);
1687 m_selection_box = m_prop.selectionbox;
1688 m_selection_box.MinEdge *= BS;
1689 m_selection_box.MaxEdge *= BS;
1691 m_tx_size.X = 1.0f / m_prop.spritediv.X;
1692 m_tx_size.Y = 1.0f / m_prop.spritediv.Y;
1694 if(!m_initial_tx_basepos_set){
1695 m_initial_tx_basepos_set = true;
1696 m_tx_basepos = m_prop.initial_sprite_basepos;
1698 if (m_is_local_player) {
1699 LocalPlayer *player = m_env->getLocalPlayer();
1700 player->makes_footstep_sound = m_prop.makes_footstep_sound;
1701 aabb3f collision_box = m_prop.collisionbox;
1702 collision_box.MinEdge *= BS;
1703 collision_box.MaxEdge *= BS;
1704 player->setCollisionbox(collision_box);
1705 player->setEyeHeight(m_prop.eye_height);
1706 player->setZoomFOV(m_prop.zoom_fov);
1709 if ((m_is_player && !m_is_local_player) && m_prop.nametag.empty())
1710 m_prop.nametag = m_name;
1711 if (m_is_local_player)
1712 m_prop.show_on_minimap = false;
1714 if (expire_visuals) {
1717 infostream << "GenericCAO: properties updated but expiring visuals"
1718 << " not necessary" << std::endl;
1719 if (textures_changed) {
1720 // don't update while punch texture modifier is active
1721 if (m_reset_textures_timer < 0)
1722 updateTextures(m_current_texture_modifier);
1727 } else if (cmd == AO_CMD_UPDATE_POSITION) {
1728 // Not sent by the server if this object is an attachment.
1729 // We might however get here if the server notices the object being detached before the client.
1730 m_position = readV3F32(is);
1731 m_velocity = readV3F32(is);
1732 m_acceleration = readV3F32(is);
1733 m_rotation = readV3F32(is);
1735 m_rotation = wrapDegrees_0_360_v3f(m_rotation);
1736 bool do_interpolate = readU8(is);
1737 bool is_end_position = readU8(is);
1738 float update_interval = readF32(is);
1740 // Place us a bit higher if we're physical, to not sink into
1741 // the ground due to sucky collision detection...
1743 m_position += v3f(0,0.002,0);
1745 if(getParent() != NULL) // Just in case
1750 if(!m_prop.physical)
1751 pos_translator.update(m_position, is_end_position, update_interval);
1753 pos_translator.init(m_position);
1755 rot_translator.update(m_rotation, false, update_interval);
1757 } else if (cmd == AO_CMD_SET_TEXTURE_MOD) {
1758 std::string mod = deSerializeString16(is);
1760 // immediately reset a engine issued texture modifier if a mod sends a different one
1761 if (m_reset_textures_timer > 0) {
1762 m_reset_textures_timer = -1;
1763 updateTextures(m_previous_texture_modifier);
1765 updateTextures(mod);
1766 } else if (cmd == AO_CMD_SET_SPRITE) {
1767 v2s16 p = readV2S16(is);
1768 int num_frames = readU16(is);
1769 float framelength = readF32(is);
1770 bool select_horiz_by_yawpitch = readU8(is);
1773 m_anim_num_frames = num_frames;
1775 m_anim_framelength = framelength;
1776 m_tx_select_horiz_by_yawpitch = select_horiz_by_yawpitch;
1779 } else if (cmd == AO_CMD_SET_PHYSICS_OVERRIDE) {
1780 float override_speed = readF32(is);
1781 float override_jump = readF32(is);
1782 float override_gravity = readF32(is);
1783 // these are sent inverted so we get true when the server sends nothing
1784 bool sneak = !readU8(is);
1785 bool sneak_glitch = !readU8(is);
1786 bool new_move = !readU8(is);
1789 if(m_is_local_player)
1791 LocalPlayer *player = m_env->getLocalPlayer();
1792 player->physics_override_speed = override_speed;
1793 player->physics_override_jump = override_jump;
1794 player->physics_override_gravity = override_gravity;
1795 player->physics_override_sneak = sneak;
1796 player->physics_override_sneak_glitch = sneak_glitch;
1797 player->physics_override_new_move = new_move;
1799 } else if (cmd == AO_CMD_SET_ANIMATION) {
1800 // TODO: change frames send as v2s32 value
1801 v2f range = readV2F32(is);
1802 if (!m_is_local_player) {
1803 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1804 m_animation_speed = readF32(is);
1805 m_animation_blend = readF32(is);
1806 // these are sent inverted so we get true when the server sends nothing
1807 m_animation_loop = !readU8(is);
1810 LocalPlayer *player = m_env->getLocalPlayer();
1811 if(player->last_animation == NO_ANIM)
1813 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1814 m_animation_speed = readF32(is);
1815 m_animation_blend = readF32(is);
1816 // these are sent inverted so we get true when the server sends nothing
1817 m_animation_loop = !readU8(is);
1819 // update animation only if local animations present
1820 // and received animation is unknown (except idle animation)
1821 bool is_known = false;
1822 for (int i = 1;i<4;i++)
1824 if(m_animation_range.Y == player->local_animations[i].Y)
1828 (player->local_animations[1].Y + player->local_animations[2].Y < 1))
1832 // FIXME: ^ This code is trash. It's also broken.
1834 } else if (cmd == AO_CMD_SET_ANIMATION_SPEED) {
1835 m_animation_speed = readF32(is);
1836 updateAnimationSpeed();
1837 } else if (cmd == AO_CMD_SET_BONE_POSITION) {
1838 std::string bone = deSerializeString16(is);
1839 v3f position = readV3F32(is);
1840 v3f rotation = readV3F32(is);
1841 m_bone_position[bone] = core::vector2d<v3f>(position, rotation);
1843 // updateBonePosition(); now called every step
1844 } else if (cmd == AO_CMD_ATTACH_TO) {
1845 u16 parent_id = readS16(is);
1846 std::string bone = deSerializeString16(is);
1847 v3f position = readV3F32(is);
1848 v3f rotation = readV3F32(is);
1849 bool force_visible = readU8(is); // Returns false for EOF
1851 setAttachment(parent_id, bone, position, rotation, force_visible);
1852 } else if (cmd == AO_CMD_PUNCHED) {
1853 u16 result_hp = readU16(is);
1855 // Use this instead of the send damage to not interfere with prediction
1856 s32 damage = (s32)m_hp - (s32)result_hp;
1860 if (m_is_local_player)
1861 m_env->getLocalPlayer()->hp = m_hp;
1867 // TODO: Execute defined fast response
1868 // As there is no definition, make a smoke puff
1869 ClientSimpleObject *simple = createSmokePuff(
1870 m_smgr, m_env, m_position,
1871 v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
1872 m_env->addSimpleObject(simple);
1873 } else if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
1874 m_reset_textures_timer = 0.05;
1876 m_reset_textures_timer += 0.05 * damage;
1877 // Cap damage overlay to 1 second
1878 m_reset_textures_timer = std::min(m_reset_textures_timer, 1.0f);
1879 updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
1884 // Same as 'Server::DiePlayer'
1885 clearParentAttachment();
1886 // Same as 'ObjectRef::l_remove'
1888 clearChildAttachments();
1890 } else if (cmd == AO_CMD_UPDATE_ARMOR_GROUPS) {
1891 m_armor_groups.clear();
1892 int armor_groups_size = readU16(is);
1893 for(int i=0; i<armor_groups_size; i++)
1895 std::string name = deSerializeString16(is);
1896 int rating = readS16(is);
1897 m_armor_groups[name] = rating;
1899 } else if (cmd == AO_CMD_SPAWN_INFANT) {
1900 u16 child_id = readU16(is);
1901 u8 type = readU8(is); // maybe this will be useful later
1904 addAttachmentChild(child_id);
1905 } else if (cmd == AO_CMD_OBSOLETE1) {
1906 // Don't do anything and also don't log a warning
1908 warningstream << FUNCTION_NAME
1909 << ": unknown command or outdated client \""
1910 << +cmd << "\"" << std::endl;
1914 /* \pre punchitem != NULL
1916 bool GenericCAO::directReportPunch(v3f dir, const ItemStack *punchitem,
1917 float time_from_last_punch)
1919 assert(punchitem); // pre-condition
1920 const ToolCapabilities *toolcap =
1921 &punchitem->getToolCapabilities(m_client->idef());
1922 PunchDamageResult result = getPunchDamage(
1926 time_from_last_punch,
1929 if(result.did_punch && result.damage != 0)
1931 if(result.damage < m_hp)
1933 m_hp -= result.damage;
1936 // TODO: Execute defined fast response
1937 // As there is no definition, make a smoke puff
1938 ClientSimpleObject *simple = createSmokePuff(
1939 m_smgr, m_env, m_position,
1940 v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
1941 m_env->addSimpleObject(simple);
1943 if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
1944 m_reset_textures_timer = 0.05;
1945 if (result.damage >= 2)
1946 m_reset_textures_timer += 0.05 * result.damage;
1947 // Cap damage overlay to 1 second
1948 m_reset_textures_timer = std::min(m_reset_textures_timer, 1.0f);
1949 updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
1956 std::string GenericCAO::debugInfoText()
1958 std::ostringstream os(std::ios::binary);
1959 os<<"GenericCAO hp="<<m_hp<<"\n";
1961 for(ItemGroupList::const_iterator i = m_armor_groups.begin();
1962 i != m_armor_groups.end(); ++i)
1964 os<<i->first<<"="<<i->second<<", ";
1970 void GenericCAO::updateMeshCulling()
1972 if (!m_is_local_player)
1975 const bool hidden = m_client->getCamera()->getCameraMode() == CAMERA_MODE_FIRST;
1977 scene::ISceneNode *node = getSceneNode();
1982 if (m_prop.visual == "upright_sprite") {
1983 // upright sprite has no backface culling
1984 node->setMaterialFlag(video::EMF_FRONT_FACE_CULLING, hidden);
1989 // Hide the mesh by culling both front and
1990 // back faces. Serious hackyness but it works for our
1991 // purposes. This also preserves the skeletal armature.
1992 node->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
1994 node->setMaterialFlag(video::EMF_FRONT_FACE_CULLING,
1997 // Restore mesh visibility.
1998 node->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
1999 m_prop.backface_culling);
2000 node->setMaterialFlag(video::EMF_FRONT_FACE_CULLING,
2006 GenericCAO proto_GenericCAO(NULL, NULL);