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"
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);
169 class TestCAO : public ClientActiveObject
172 TestCAO(Client *client, ClientEnvironment *env);
173 virtual ~TestCAO() = default;
175 ActiveObjectType getType() const
177 return ACTIVEOBJECT_TYPE_TEST;
180 static ClientActiveObject* create(Client *client, ClientEnvironment *env);
182 void addToScene(ITextureSource *tsrc);
183 void removeFromScene(bool permanent);
184 void updateLight(u32 day_night_ratio);
185 void updateNodePos();
187 void step(float dtime, ClientEnvironment *env);
189 void processMessage(const std::string &data);
191 bool getCollisionBox(aabb3f *toset) const { return false; }
193 scene::IMeshSceneNode *m_node;
198 TestCAO proto_TestCAO(NULL, NULL);
200 TestCAO::TestCAO(Client *client, ClientEnvironment *env):
201 ClientActiveObject(0, client, env),
203 m_position(v3f(0,10*BS,0))
205 ClientActiveObject::registerType(getType(), create);
208 ClientActiveObject* TestCAO::create(Client *client, ClientEnvironment *env)
210 return new TestCAO(client, env);
213 void TestCAO::addToScene(ITextureSource *tsrc)
218 //video::IVideoDriver* driver = smgr->getVideoDriver();
220 scene::SMesh *mesh = new scene::SMesh();
221 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
222 video::SColor c(255,255,255,255);
223 video::S3DVertex vertices[4] =
225 video::S3DVertex(-BS/2,-BS/4,0, 0,0,0, c, 0,1),
226 video::S3DVertex(BS/2,-BS/4,0, 0,0,0, c, 1,1),
227 video::S3DVertex(BS/2,BS/4,0, 0,0,0, c, 1,0),
228 video::S3DVertex(-BS/2,BS/4,0, 0,0,0, c, 0,0),
230 u16 indices[] = {0,1,2,2,3,0};
231 buf->append(vertices, 4, indices, 6);
233 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
234 buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
235 buf->getMaterial().setTexture(0, tsrc->getTextureForMesh("rat.png"));
236 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
237 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
238 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
240 mesh->addMeshBuffer(buf);
242 m_node = RenderingEngine::get_scene_manager()->addMeshSceneNode(mesh, NULL);
247 void TestCAO::removeFromScene(bool permanent)
256 void TestCAO::updateLight(u32 day_night_ratio)
260 void TestCAO::updateNodePos()
265 m_node->setPosition(m_position);
266 //m_node->setRotation(v3f(0, 45, 0));
269 void TestCAO::step(float dtime, ClientEnvironment *env)
273 v3f rot = m_node->getRotation();
274 //infostream<<"dtime="<<dtime<<", rot.Y="<<rot.Y<<std::endl;
275 rot.Y += dtime * 180;
276 m_node->setRotation(rot);
280 void TestCAO::processMessage(const std::string &data)
282 infostream<<"TestCAO: Got data: "<<data<<std::endl;
283 std::istringstream is(data, std::ios::binary);
301 #include "clientobject.h"
303 GenericCAO::GenericCAO(Client *client, ClientEnvironment *env):
304 ClientActiveObject(0, client, env)
306 if (client == NULL) {
307 ClientActiveObject::registerType(getType(), create);
313 bool GenericCAO::getCollisionBox(aabb3f *toset) const
317 //update collision box
318 toset->MinEdge = m_prop.collisionbox.MinEdge * BS;
319 toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS;
321 toset->MinEdge += m_position;
322 toset->MaxEdge += m_position;
330 bool GenericCAO::collideWithObjects() const
332 return m_prop.collideWithObjects;
335 void GenericCAO::initialize(const std::string &data)
337 infostream<<"GenericCAO: Got init data"<<std::endl;
338 processInitData(data);
341 // Check if it's the current player
342 LocalPlayer *player = m_env->getLocalPlayer();
343 if (player && strcmp(player->getName(), m_name.c_str()) == 0) {
344 m_is_local_player = true;
345 m_is_visible = false;
346 player->setCAO(this);
350 m_enable_shaders = g_settings->getBool("enable_shaders");
353 void GenericCAO::processInitData(const std::string &data)
355 std::istringstream is(data, std::ios::binary);
356 const u8 version = readU8(is);
359 errorstream << "GenericCAO: Unsupported init data version"
364 // PROTOCOL_VERSION >= 37
365 m_name = deSerializeString(is);
366 m_is_player = readU8(is);
368 m_position = readV3F32(is);
369 m_rotation = readV3F32(is);
372 const u8 num_messages = readU8(is);
374 for (int i = 0; i < num_messages; i++) {
375 std::string message = deSerializeLongString(is);
376 processMessage(message);
379 m_rotation = wrapDegrees_0_360_v3f(m_rotation);
380 pos_translator.init(m_position);
381 rot_translator.init(m_rotation);
385 GenericCAO::~GenericCAO()
387 removeFromScene(true);
390 bool GenericCAO::getSelectionBox(aabb3f *toset) const
392 if (!m_prop.is_visible || !m_is_visible || m_is_local_player
393 || !m_prop.pointable) {
396 *toset = m_selection_box;
400 const v3f GenericCAO::getPosition() const
403 return pos_translator.val_current;
405 // Calculate real position in world based on MatrixNode
407 v3s16 camera_offset = m_env->getCameraOffset();
408 return m_matrixnode->getAbsolutePosition() +
409 intToFloat(camera_offset, BS);
415 const bool GenericCAO::isImmortal()
417 return itemgroup_get(getGroups(), "immortal");
420 scene::ISceneNode *GenericCAO::getSceneNode() const
426 if (m_animated_meshnode) {
427 return m_animated_meshnode;
430 if (m_wield_meshnode) {
431 return m_wield_meshnode;
440 scene::IAnimatedMeshSceneNode *GenericCAO::getAnimatedMeshSceneNode() const
442 return m_animated_meshnode;
445 void GenericCAO::setChildrenVisible(bool toset)
447 for (u16 cao_id : m_attachment_child_ids) {
448 GenericCAO *obj = m_env->getGenericCAO(cao_id);
450 obj->setVisible(toset);
455 void GenericCAO::setAttachment(int parent_id, const std::string &bone, v3f position, v3f rotation)
457 int old_parent = m_attachment_parent_id;
458 m_attachment_parent_id = parent_id;
459 m_attachment_bone = bone;
460 m_attachment_position = position;
461 m_attachment_rotation = rotation;
463 ClientActiveObject *parent = m_env->getActiveObject(parent_id);
465 if (parent_id != old_parent) {
466 if (auto *o = m_env->getActiveObject(old_parent))
467 o->removeAttachmentChild(m_id);
469 parent->addAttachmentChild(m_id);
476 void GenericCAO::getAttachment(int *parent_id, std::string *bone, v3f *position,
479 *parent_id = m_attachment_parent_id;
480 *bone = m_attachment_bone;
481 *position = m_attachment_position;
482 *rotation = m_attachment_rotation;
485 void GenericCAO::clearChildAttachments()
487 // Cannot use for-loop here: setAttachment() modifies 'm_attachment_child_ids'!
488 while (!m_attachment_child_ids.empty()) {
489 int child_id = *m_attachment_child_ids.begin();
491 if (ClientActiveObject *child = m_env->getActiveObject(child_id))
492 child->setAttachment(0, "", v3f(), v3f());
494 removeAttachmentChild(child_id);
498 void GenericCAO::clearParentAttachment()
500 if (m_attachment_parent_id)
501 setAttachment(0, "", m_attachment_position, m_attachment_rotation);
503 setAttachment(0, "", v3f(), v3f());
506 void GenericCAO::addAttachmentChild(int child_id)
508 m_attachment_child_ids.insert(child_id);
511 void GenericCAO::removeAttachmentChild(int child_id)
513 m_attachment_child_ids.erase(child_id);
516 ClientActiveObject* GenericCAO::getParent() const
518 return m_attachment_parent_id ? m_env->getActiveObject(m_attachment_parent_id) :
522 void GenericCAO::removeFromScene(bool permanent)
524 // Should be true when removing the object permanently
525 // and false when refreshing (eg: updating visuals)
526 if (m_env && permanent) {
527 // The client does not know whether this object does re-appear to
528 // a later time, thus do not clear child attachments.
530 clearParentAttachment();
534 m_meshnode->remove();
536 m_meshnode = nullptr;
537 } else if (m_animated_meshnode) {
538 m_animated_meshnode->remove();
539 m_animated_meshnode->drop();
540 m_animated_meshnode = nullptr;
541 } else if (m_wield_meshnode) {
542 m_wield_meshnode->remove();
543 m_wield_meshnode->drop();
544 m_wield_meshnode = nullptr;
545 } else if (m_spritenode) {
546 m_spritenode->remove();
547 m_spritenode->drop();
548 m_spritenode = nullptr;
552 m_matrixnode->remove();
553 m_matrixnode->drop();
554 m_matrixnode = nullptr;
558 m_client->getCamera()->removeNametag(m_nametag);
563 void GenericCAO::addToScene(ITextureSource *tsrc)
565 m_smgr = RenderingEngine::get_scene_manager();
567 if (getSceneNode() != NULL) {
571 m_visuals_expired = false;
573 if (!m_prop.is_visible)
576 infostream << "GenericCAO::addToScene(): " << m_prop.visual << std::endl;
578 if (m_enable_shaders) {
579 IShaderSource *shader_source = m_client->getShaderSource();
580 u32 shader_id = shader_source->getShader(
582 (m_prop.use_texture_alpha) ? TILE_MATERIAL_ALPHA : TILE_MATERIAL_BASIC,
584 m_material_type = shader_source->getShaderInfo(shader_id).material;
586 m_material_type = (m_prop.use_texture_alpha) ?
587 video::EMT_TRANSPARENT_ALPHA_CHANNEL : video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
590 auto grabMatrixNode = [this] {
591 m_matrixnode = RenderingEngine::get_scene_manager()->
592 addDummyTransformationSceneNode();
593 m_matrixnode->grab();
596 auto setSceneNodeMaterial = [this] (scene::ISceneNode *node) {
597 node->setMaterialFlag(video::EMF_LIGHTING, false);
598 node->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
599 node->setMaterialFlag(video::EMF_FOG_ENABLE, true);
600 node->setMaterialType(m_material_type);
602 if (m_enable_shaders) {
603 node->setMaterialFlag(video::EMF_GOURAUD_SHADING, false);
604 node->setMaterialFlag(video::EMF_NORMALIZE_NORMALS, true);
608 if (m_prop.visual == "sprite") {
610 m_spritenode = RenderingEngine::get_scene_manager()->addBillboardSceneNode(
611 m_matrixnode, v2f(1, 1), v3f(0,0,0), -1);
612 m_spritenode->grab();
613 m_spritenode->setMaterialTexture(0,
614 tsrc->getTextureForMesh("unknown_node.png"));
616 setSceneNodeMaterial(m_spritenode);
618 m_spritenode->setSize(v2f(m_prop.visual_size.X,
619 m_prop.visual_size.Y) * BS);
621 const float txs = 1.0 / 1;
622 const float tys = 1.0 / 1;
623 setBillboardTextureMatrix(m_spritenode,
626 } else if (m_prop.visual == "upright_sprite") {
628 scene::SMesh *mesh = new scene::SMesh();
629 double dx = BS * m_prop.visual_size.X / 2;
630 double dy = BS * m_prop.visual_size.Y / 2;
631 video::SColor c(0xFFFFFFFF);
634 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
635 video::S3DVertex vertices[4] = {
636 video::S3DVertex(-dx, -dy, 0, 0,0,1, c, 1,1),
637 video::S3DVertex( dx, -dy, 0, 0,0,1, c, 0,1),
638 video::S3DVertex( dx, dy, 0, 0,0,1, c, 0,0),
639 video::S3DVertex(-dx, dy, 0, 0,0,1, c, 1,0),
642 // Move minimal Y position to 0 (feet position)
643 for (video::S3DVertex &vertex : vertices)
646 u16 indices[] = {0,1,2,2,3,0};
647 buf->append(vertices, 4, indices, 6);
649 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
650 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
651 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
652 buf->getMaterial().MaterialType = m_material_type;
654 if (m_enable_shaders) {
655 buf->getMaterial().EmissiveColor = c;
656 buf->getMaterial().setFlag(video::EMF_GOURAUD_SHADING, false);
657 buf->getMaterial().setFlag(video::EMF_NORMALIZE_NORMALS, true);
661 mesh->addMeshBuffer(buf);
665 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
666 video::S3DVertex vertices[4] = {
667 video::S3DVertex( dx,-dy, 0, 0,0,-1, c, 1,1),
668 video::S3DVertex(-dx,-dy, 0, 0,0,-1, c, 0,1),
669 video::S3DVertex(-dx, dy, 0, 0,0,-1, c, 0,0),
670 video::S3DVertex( dx, dy, 0, 0,0,-1, c, 1,0),
673 // Move minimal Y position to 0 (feet position)
674 for (video::S3DVertex &vertex : vertices)
677 u16 indices[] = {0,1,2,2,3,0};
678 buf->append(vertices, 4, indices, 6);
680 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
681 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
682 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
683 buf->getMaterial().MaterialType = m_material_type;
685 if (m_enable_shaders) {
686 buf->getMaterial().EmissiveColor = c;
687 buf->getMaterial().setFlag(video::EMF_GOURAUD_SHADING, false);
688 buf->getMaterial().setFlag(video::EMF_NORMALIZE_NORMALS, true);
692 mesh->addMeshBuffer(buf);
695 m_meshnode = RenderingEngine::get_scene_manager()->
696 addMeshSceneNode(mesh, m_matrixnode);
699 // Set it to use the materials of the meshbuffers directly.
700 // This is needed for changing the texture in the future
701 m_meshnode->setReadOnlyMaterials(true);
702 } else if (m_prop.visual == "cube") {
704 scene::IMesh *mesh = createCubeMesh(v3f(BS,BS,BS));
705 m_meshnode = RenderingEngine::get_scene_manager()->
706 addMeshSceneNode(mesh, m_matrixnode);
710 m_meshnode->setScale(m_prop.visual_size);
711 m_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
712 m_prop.backface_culling);
714 setSceneNodeMaterial(m_meshnode);
715 } else if (m_prop.visual == "mesh") {
717 scene::IAnimatedMesh *mesh = m_client->getMesh(m_prop.mesh, true);
719 m_animated_meshnode = RenderingEngine::get_scene_manager()->
720 addAnimatedMeshSceneNode(mesh, m_matrixnode);
721 m_animated_meshnode->grab();
722 mesh->drop(); // The scene node took hold of it
724 if (!checkMeshNormals(mesh)) {
725 infostream << "GenericCAO: recalculating normals for mesh "
726 << m_prop.mesh << std::endl;
727 m_smgr->getMeshManipulator()->
728 recalculateNormals(mesh, true, false);
731 m_animated_meshnode->animateJoints(); // Needed for some animations
732 m_animated_meshnode->setScale(m_prop.visual_size);
734 // set vertex colors to ensure alpha is set
735 setMeshColor(m_animated_meshnode->getMesh(), video::SColor(0xFFFFFFFF));
737 setAnimatedMeshColor(m_animated_meshnode, video::SColor(0xFFFFFFFF));
739 setSceneNodeMaterial(m_animated_meshnode);
741 m_animated_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
742 m_prop.backface_culling);
744 errorstream<<"GenericCAO::addToScene(): Could not load mesh "<<m_prop.mesh<<std::endl;
745 } else if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
748 if (m_prop.wield_item.empty()) {
749 // Old format, only textures are specified.
750 infostream << "textures: " << m_prop.textures.size() << std::endl;
751 if (!m_prop.textures.empty()) {
752 infostream << "textures[0]: " << m_prop.textures[0]
754 IItemDefManager *idef = m_client->idef();
755 item = ItemStack(m_prop.textures[0], 1, 0, idef);
758 infostream << "serialized form: " << m_prop.wield_item << std::endl;
759 item.deSerialize(m_prop.wield_item, m_client->idef());
761 m_wield_meshnode = new WieldMeshSceneNode(
762 RenderingEngine::get_scene_manager(), -1);
763 m_wield_meshnode->setItem(item, m_client,
764 (m_prop.visual == "wielditem"));
766 m_wield_meshnode->setScale(m_prop.visual_size / 2.0f);
767 m_wield_meshnode->setColor(video::SColor(0xFFFFFFFF));
769 infostream<<"GenericCAO::addToScene(): \""<<m_prop.visual
770 <<"\" not supported"<<std::endl;
773 /* don't update while punch texture modifier is active */
774 if (m_reset_textures_timer < 0)
775 updateTextures(m_current_texture_modifier);
777 scene::ISceneNode *node = getSceneNode();
779 if (node && m_matrixnode)
780 node->setParent(m_matrixnode);
785 updateBonePosition();
787 setNodeLight(m_last_light);
790 void GenericCAO::updateLight(u32 day_night_ratio)
799 u16 npos = getLightPosition(pos);
800 for (u16 i = 0; i < npos; i++) {
802 MapNode n = m_env->getMap().getNode(pos[i], &this_ok);
804 u8 this_light = n.getLightBlend(day_night_ratio, m_client->ndef());
805 light_at_pos = MYMAX(light_at_pos, this_light);
810 light_at_pos = blend_light(day_night_ratio, LIGHT_SUN, 0);
812 u8 light = decode_light(light_at_pos + m_glow);
813 if (light != m_last_light) {
814 m_last_light = light;
819 void GenericCAO::setNodeLight(u8 light)
821 video::SColor color(255, light, light, light);
823 if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
824 if (m_wield_meshnode)
825 m_wield_meshnode->setNodeLightColor(color);
829 if (m_enable_shaders) {
830 if (m_prop.visual == "upright_sprite") {
834 scene::IMesh *mesh = m_meshnode->getMesh();
835 for (u32 i = 0; i < mesh->getMeshBufferCount(); ++i) {
836 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
837 buf->getMaterial().EmissiveColor = color;
840 scene::ISceneNode *node = getSceneNode();
844 for (u32 i = 0; i < node->getMaterialCount(); ++i) {
845 video::SMaterial &material = node->getMaterial(i);
846 material.EmissiveColor = color;
851 setMeshColor(m_meshnode->getMesh(), color);
852 } else if (m_animated_meshnode) {
853 setAnimatedMeshColor(m_animated_meshnode, color);
854 } else if (m_spritenode) {
855 m_spritenode->setColor(color);
860 u16 GenericCAO::getLightPosition(v3s16 *pos)
862 const auto &box = m_prop.collisionbox;
863 pos[0] = floatToInt(m_position + box.MinEdge * BS, BS);
864 pos[1] = floatToInt(m_position + box.MaxEdge * BS, BS);
866 // Skip center pos if it falls into the same node as Min or MaxEdge
867 if ((box.MaxEdge - box.MinEdge).getLengthSQ() < 3.0f)
869 pos[2] = floatToInt(m_position + box.getCenter() * BS, BS);
873 void GenericCAO::updateNametag()
875 if (m_is_local_player) // No nametag for local player
878 if (m_prop.nametag.empty()) {
881 m_client->getCamera()->removeNametag(m_nametag);
887 scene::ISceneNode *node = getSceneNode();
892 pos.Y = m_prop.selectionbox.MaxEdge.Y + 0.3f;
895 m_nametag = m_client->getCamera()->addNametag(node,
896 m_prop.nametag, m_prop.nametag_color, pos);
899 m_nametag->nametag_text = m_prop.nametag;
900 m_nametag->nametag_color = m_prop.nametag_color;
901 m_nametag->nametag_pos = pos;
905 void GenericCAO::updateNodePos()
907 if (getParent() != NULL)
910 scene::ISceneNode *node = getSceneNode();
913 v3s16 camera_offset = m_env->getCameraOffset();
914 v3f pos = pos_translator.val_current -
915 intToFloat(camera_offset, BS);
916 getPosRotMatrix().setTranslation(pos);
917 if (node != m_spritenode) { // rotate if not a sprite
918 v3f rot = m_is_local_player ? -m_rotation : -rot_translator.val_current;
919 setPitchYawRoll(getPosRotMatrix(), rot);
924 void GenericCAO::step(float dtime, ClientEnvironment *env)
926 if (m_animated_meshnode) {
927 m_animated_meshnode->animateJoints();
928 updateBonePosition();
931 // Handle model animations and update positions instantly to prevent lags
932 if (m_is_local_player) {
933 LocalPlayer *player = m_env->getLocalPlayer();
934 m_position = player->getPosition();
935 pos_translator.val_current = m_position;
936 m_rotation.Y = wrapDegrees_0_360(player->getYaw());
937 rot_translator.val_current = m_rotation;
940 int old_anim = player->last_animation;
941 float old_anim_speed = player->last_animation_speed;
942 m_velocity = v3f(0,0,0);
943 m_acceleration = v3f(0,0,0);
944 const PlayerControl &controls = player->getPlayerControl();
946 bool walking = false;
947 if (controls.up || controls.down || controls.left || controls.right ||
948 controls.forw_move_joystick_axis != 0.f ||
949 controls.sidew_move_joystick_axis != 0.f)
952 f32 new_speed = player->local_animation_speed;
953 v2s32 new_anim = v2s32(0,0);
954 bool allow_update = false;
956 // increase speed if using fast or flying fast
957 if((g_settings->getBool("fast_move") &&
958 m_client->checkLocalPrivilege("fast")) &&
960 (!player->touching_ground &&
961 g_settings->getBool("free_move") &&
962 m_client->checkLocalPrivilege("fly"))))
964 // slowdown speed if sneeking
965 if (controls.sneak && walking)
968 if (walking && (controls.LMB || controls.RMB)) {
969 new_anim = player->local_animations[3];
970 player->last_animation = WD_ANIM;
972 new_anim = player->local_animations[1];
973 player->last_animation = WALK_ANIM;
974 } else if(controls.LMB || controls.RMB) {
975 new_anim = player->local_animations[2];
976 player->last_animation = DIG_ANIM;
979 // Apply animations if input detected and not attached
980 // or set idle animation
981 if ((new_anim.X + new_anim.Y) > 0 && !getParent()) {
983 m_animation_range = new_anim;
984 m_animation_speed = new_speed;
985 player->last_animation_speed = m_animation_speed;
987 player->last_animation = NO_ANIM;
989 if (old_anim != NO_ANIM) {
990 m_animation_range = player->local_animations[0];
995 // Update local player animations
996 if ((player->last_animation != old_anim ||
997 m_animation_speed != old_anim_speed) &&
998 player->last_animation != NO_ANIM && allow_update)
1004 if (m_visuals_expired && m_smgr) {
1005 m_visuals_expired = false;
1007 // Attachments, part 1: All attached objects must be unparented first,
1008 // or Irrlicht causes a segmentation fault
1009 for (u16 cao_id : m_attachment_child_ids) {
1010 ClientActiveObject *obj = m_env->getActiveObject(cao_id);
1012 scene::ISceneNode *child_node = obj->getSceneNode();
1013 // The node's parent is always an IDummyTraformationSceneNode,
1014 // so we need to reparent that one instead.
1016 child_node->getParent()->setParent(m_smgr->getRootSceneNode());
1020 removeFromScene(false);
1021 addToScene(m_client->tsrc());
1023 // Attachments, part 2: Now that the parent has been refreshed, put its attachments back
1024 for (u16 cao_id : m_attachment_child_ids) {
1025 ClientActiveObject *obj = m_env->getActiveObject(cao_id);
1027 obj->updateAttachments();
1031 // Make sure m_is_visible is always applied
1032 scene::ISceneNode *node = getSceneNode();
1034 node->setVisible(m_is_visible);
1036 if(getParent() != NULL) // Attachments should be glued to their parent by Irrlicht
1038 // Set these for later
1039 m_position = getPosition();
1040 m_velocity = v3f(0,0,0);
1041 m_acceleration = v3f(0,0,0);
1042 pos_translator.val_current = m_position;
1043 pos_translator.val_target = m_position;
1045 rot_translator.translate(dtime);
1046 v3f lastpos = pos_translator.val_current;
1050 aabb3f box = m_prop.collisionbox;
1053 collisionMoveResult moveresult;
1054 f32 pos_max_d = BS*0.125; // Distance per iteration
1055 v3f p_pos = m_position;
1056 v3f p_velocity = m_velocity;
1057 moveresult = collisionMoveSimple(env,env->getGameDef(),
1058 pos_max_d, box, m_prop.stepheight, dtime,
1059 &p_pos, &p_velocity, m_acceleration,
1060 this, m_prop.collideWithObjects);
1063 m_velocity = p_velocity;
1065 bool is_end_position = moveresult.collides;
1066 pos_translator.update(m_position, is_end_position, dtime);
1068 m_position += dtime * m_velocity + 0.5 * dtime * dtime * m_acceleration;
1069 m_velocity += dtime * m_acceleration;
1070 pos_translator.update(m_position, pos_translator.aim_is_end,
1071 pos_translator.anim_time);
1073 pos_translator.translate(dtime);
1076 float moved = lastpos.getDistanceFrom(pos_translator.val_current);
1077 m_step_distance_counter += moved;
1078 if (m_step_distance_counter > 1.5f * BS) {
1079 m_step_distance_counter = 0.0f;
1080 if (!m_is_local_player && m_prop.makes_footstep_sound) {
1081 const NodeDefManager *ndef = m_client->ndef();
1082 v3s16 p = floatToInt(getPosition() +
1083 v3f(0.0f, (m_prop.collisionbox.MinEdge.Y - 0.5f) * BS, 0.0f), BS);
1084 MapNode n = m_env->getMap().getNode(p);
1085 SimpleSoundSpec spec = ndef->get(n).sound_footstep;
1086 // Reduce footstep gain, as non-local-player footsteps are
1089 m_client->sound()->playSoundAt(spec, false, getPosition());
1094 m_anim_timer += dtime;
1095 if(m_anim_timer >= m_anim_framelength)
1097 m_anim_timer -= m_anim_framelength;
1099 if(m_anim_frame >= m_anim_num_frames)
1105 if(m_reset_textures_timer >= 0)
1107 m_reset_textures_timer -= dtime;
1108 if(m_reset_textures_timer <= 0) {
1109 m_reset_textures_timer = -1;
1110 updateTextures(m_previous_texture_modifier);
1114 if (!getParent() && std::fabs(m_prop.automatic_rotate) > 0.001) {
1115 // This is the child node's rotation. It is only used for automatic_rotate.
1116 v3f local_rot = node->getRotation();
1117 local_rot.Y = modulo360f(local_rot.Y - dtime * core::RADTODEG *
1118 m_prop.automatic_rotate);
1119 node->setRotation(local_rot);
1122 if (!getParent() && m_prop.automatic_face_movement_dir &&
1123 (fabs(m_velocity.Z) > 0.001 || fabs(m_velocity.X) > 0.001)) {
1124 float target_yaw = atan2(m_velocity.Z, m_velocity.X) * 180 / M_PI
1125 + m_prop.automatic_face_movement_dir_offset;
1126 float max_rotation_per_sec =
1127 m_prop.automatic_face_movement_max_rotation_per_sec;
1129 if (max_rotation_per_sec > 0) {
1130 wrappedApproachShortest(m_rotation.Y, target_yaw,
1131 dtime * max_rotation_per_sec, 360.f);
1133 // Negative values of max_rotation_per_sec mean disabled.
1134 m_rotation.Y = target_yaw;
1137 rot_translator.val_current = m_rotation;
1142 void GenericCAO::updateTexturePos()
1146 scene::ICameraSceneNode* camera =
1147 m_spritenode->getSceneManager()->getActiveCamera();
1150 v3f cam_to_entity = m_spritenode->getAbsolutePosition()
1151 - camera->getAbsolutePosition();
1152 cam_to_entity.normalize();
1154 int row = m_tx_basepos.Y;
1155 int col = m_tx_basepos.X;
1157 if (m_tx_select_horiz_by_yawpitch) {
1158 if (cam_to_entity.Y > 0.75)
1160 else if (cam_to_entity.Y < -0.75)
1164 atan2(cam_to_entity.Z, cam_to_entity.X) / M_PI * 180.;
1165 float dir = mob_dir - m_rotation.Y;
1166 dir = wrapDegrees_180(dir);
1167 if (std::fabs(wrapDegrees_180(dir - 0)) <= 45.1f)
1169 else if(std::fabs(wrapDegrees_180(dir - 90)) <= 45.1f)
1171 else if(std::fabs(wrapDegrees_180(dir - 180)) <= 45.1f)
1173 else if(std::fabs(wrapDegrees_180(dir + 90)) <= 45.1f)
1180 // Animation goes downwards
1181 row += m_anim_frame;
1183 float txs = m_tx_size.X;
1184 float tys = m_tx_size.Y;
1185 setBillboardTextureMatrix(m_spritenode, txs, tys, col, row);
1189 // Do not pass by reference, see header.
1190 void GenericCAO::updateTextures(std::string mod)
1192 ITextureSource *tsrc = m_client->tsrc();
1194 bool use_trilinear_filter = g_settings->getBool("trilinear_filter");
1195 bool use_bilinear_filter = g_settings->getBool("bilinear_filter");
1196 bool use_anisotropic_filter = g_settings->getBool("anisotropic_filter");
1198 m_previous_texture_modifier = m_current_texture_modifier;
1199 m_current_texture_modifier = mod;
1200 m_glow = m_prop.glow;
1203 if (m_prop.visual == "sprite") {
1204 std::string texturestring = "unknown_node.png";
1205 if (!m_prop.textures.empty())
1206 texturestring = m_prop.textures[0];
1207 texturestring += mod;
1208 m_spritenode->getMaterial(0).MaterialType = m_material_type;
1209 m_spritenode->getMaterial(0).MaterialTypeParam = 0.5f;
1210 m_spritenode->setMaterialTexture(0,
1211 tsrc->getTextureForMesh(texturestring));
1213 // This allows setting per-material colors. However, until a real lighting
1214 // system is added, the code below will have no effect. Once MineTest
1215 // has directional lighting, it should work automatically.
1216 if (!m_prop.colors.empty()) {
1217 m_spritenode->getMaterial(0).AmbientColor = m_prop.colors[0];
1218 m_spritenode->getMaterial(0).DiffuseColor = m_prop.colors[0];
1219 m_spritenode->getMaterial(0).SpecularColor = m_prop.colors[0];
1222 m_spritenode->getMaterial(0).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1223 m_spritenode->getMaterial(0).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1224 m_spritenode->getMaterial(0).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1228 if (m_animated_meshnode) {
1229 if (m_prop.visual == "mesh") {
1230 for (u32 i = 0; i < m_prop.textures.size() &&
1231 i < m_animated_meshnode->getMaterialCount(); ++i) {
1232 std::string texturestring = m_prop.textures[i];
1233 if (texturestring.empty())
1234 continue; // Empty texture string means don't modify that material
1235 texturestring += mod;
1236 video::ITexture* texture = tsrc->getTextureForMesh(texturestring);
1238 errorstream<<"GenericCAO::updateTextures(): Could not load texture "<<texturestring<<std::endl;
1242 // Set material flags and texture
1243 video::SMaterial& material = m_animated_meshnode->getMaterial(i);
1244 material.MaterialType = m_material_type;
1245 material.MaterialTypeParam = 0.5f;
1246 material.TextureLayer[0].Texture = texture;
1247 material.setFlag(video::EMF_LIGHTING, true);
1248 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1249 material.setFlag(video::EMF_BACK_FACE_CULLING, m_prop.backface_culling);
1251 // don't filter low-res textures, makes them look blurry
1252 // player models have a res of 64
1253 const core::dimension2d<u32> &size = texture->getOriginalSize();
1254 const u32 res = std::min(size.Height, size.Width);
1255 use_trilinear_filter &= res > 64;
1256 use_bilinear_filter &= res > 64;
1258 m_animated_meshnode->getMaterial(i)
1259 .setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1260 m_animated_meshnode->getMaterial(i)
1261 .setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1262 m_animated_meshnode->getMaterial(i)
1263 .setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1265 for (u32 i = 0; i < m_prop.colors.size() &&
1266 i < m_animated_meshnode->getMaterialCount(); ++i)
1268 // This allows setting per-material colors. However, until a real lighting
1269 // system is added, the code below will have no effect. Once MineTest
1270 // has directional lighting, it should work automatically.
1271 m_animated_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1272 m_animated_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1273 m_animated_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1279 if(m_prop.visual == "cube")
1281 for (u32 i = 0; i < 6; ++i)
1283 std::string texturestring = "unknown_node.png";
1284 if(m_prop.textures.size() > i)
1285 texturestring = m_prop.textures[i];
1286 texturestring += mod;
1289 // Set material flags and texture
1290 video::SMaterial& material = m_meshnode->getMaterial(i);
1291 material.MaterialType = m_material_type;
1292 material.MaterialTypeParam = 0.5f;
1293 material.setFlag(video::EMF_LIGHTING, false);
1294 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1295 material.setTexture(0,
1296 tsrc->getTextureForMesh(texturestring));
1297 material.getTextureMatrix(0).makeIdentity();
1299 // This allows setting per-material colors. However, until a real lighting
1300 // system is added, the code below will have no effect. Once MineTest
1301 // has directional lighting, it should work automatically.
1302 if(m_prop.colors.size() > i)
1304 m_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1305 m_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1306 m_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1309 m_meshnode->getMaterial(i).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1310 m_meshnode->getMaterial(i).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1311 m_meshnode->getMaterial(i).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1313 } else if (m_prop.visual == "upright_sprite") {
1314 scene::IMesh *mesh = m_meshnode->getMesh();
1316 std::string tname = "unknown_object.png";
1317 if (!m_prop.textures.empty())
1318 tname = m_prop.textures[0];
1320 scene::IMeshBuffer *buf = mesh->getMeshBuffer(0);
1321 buf->getMaterial().setTexture(0,
1322 tsrc->getTextureForMesh(tname));
1324 // This allows setting per-material colors. However, until a real lighting
1325 // system is added, the code below will have no effect. Once MineTest
1326 // has directional lighting, it should work automatically.
1327 if(!m_prop.colors.empty()) {
1328 buf->getMaterial().AmbientColor = m_prop.colors[0];
1329 buf->getMaterial().DiffuseColor = m_prop.colors[0];
1330 buf->getMaterial().SpecularColor = m_prop.colors[0];
1333 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1334 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1335 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1338 std::string tname = "unknown_object.png";
1339 if (m_prop.textures.size() >= 2)
1340 tname = m_prop.textures[1];
1341 else if (!m_prop.textures.empty())
1342 tname = m_prop.textures[0];
1344 scene::IMeshBuffer *buf = mesh->getMeshBuffer(1);
1345 buf->getMaterial().setTexture(0,
1346 tsrc->getTextureForMesh(tname));
1348 // This allows setting per-material colors. However, until a real lighting
1349 // system is added, the code below will have no effect. Once MineTest
1350 // has directional lighting, it should work automatically.
1351 if (m_prop.colors.size() >= 2) {
1352 buf->getMaterial().AmbientColor = m_prop.colors[1];
1353 buf->getMaterial().DiffuseColor = m_prop.colors[1];
1354 buf->getMaterial().SpecularColor = m_prop.colors[1];
1355 } else if (!m_prop.colors.empty()) {
1356 buf->getMaterial().AmbientColor = m_prop.colors[0];
1357 buf->getMaterial().DiffuseColor = m_prop.colors[0];
1358 buf->getMaterial().SpecularColor = m_prop.colors[0];
1361 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1362 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1363 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1365 // Set mesh color (only if lighting is disabled)
1366 if (!m_prop.colors.empty() && m_glow < 0)
1367 setMeshColor(mesh, m_prop.colors[0]);
1372 void GenericCAO::updateAnimation()
1374 if (!m_animated_meshnode)
1377 if (m_animated_meshnode->getStartFrame() != m_animation_range.X ||
1378 m_animated_meshnode->getEndFrame() != m_animation_range.Y)
1379 m_animated_meshnode->setFrameLoop(m_animation_range.X, m_animation_range.Y);
1380 if (m_animated_meshnode->getAnimationSpeed() != m_animation_speed)
1381 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1382 m_animated_meshnode->setTransitionTime(m_animation_blend);
1383 // Requires Irrlicht 1.8 or greater
1384 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR > 1
1385 if (m_animated_meshnode->getLoopMode() != m_animation_loop)
1386 m_animated_meshnode->setLoopMode(m_animation_loop);
1390 void GenericCAO::updateAnimationSpeed()
1392 if (!m_animated_meshnode)
1395 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1398 void GenericCAO::updateBonePosition()
1400 if (m_bone_position.empty() || !m_animated_meshnode)
1403 m_animated_meshnode->setJointMode(irr::scene::EJUOR_CONTROL); // To write positions to the mesh on render
1404 for (auto &it : m_bone_position) {
1405 std::string bone_name = it.first;
1406 irr::scene::IBoneSceneNode* bone = m_animated_meshnode->getJointNode(bone_name.c_str());
1408 bone->setPosition(it.second.X);
1409 bone->setRotation(it.second.Y);
1413 // search through bones to find mistakenly rotated bones due to bug in Irrlicht
1414 for (u32 i = 0; i < m_animated_meshnode->getJointCount(); ++i) {
1415 irr::scene::IBoneSceneNode *bone = m_animated_meshnode->getJointNode(i);
1419 //If bone is manually positioned there is no need to perform the bug check
1421 for (auto &it : m_bone_position) {
1422 if (it.first == bone->getName()) {
1430 // Workaround for Irrlicht bug
1431 // We check each bone to see if it has been rotated ~180deg from its expected position due to a bug in Irricht
1432 // when using EJUOR_CONTROL joint control. If the bug is detected we update the bone to the proper position
1433 // and update the bones transformation.
1434 v3f bone_rot = bone->getRelativeTransformation().getRotationDegrees();
1435 float offset = fabsf(bone_rot.X - bone->getRotation().X);
1436 if (offset > 179.9f && offset < 180.1f) {
1437 bone->setRotation(bone_rot);
1438 bone->updateAbsolutePosition();
1443 void GenericCAO::updateAttachments()
1445 ClientActiveObject *parent = getParent();
1447 m_attached_to_local = parent && parent->isLocalPlayer();
1450 Following cases exist:
1451 m_attachment_parent_id == 0 && !parent
1452 This object is not attached
1453 m_attachment_parent_id != 0 && parent
1454 This object is attached
1455 m_attachment_parent_id != 0 && !parent
1456 This object will be attached as soon the parent is known
1457 m_attachment_parent_id == 0 && parent
1461 if (!parent) { // Detach or don't attach
1463 v3s16 camera_offset = m_env->getCameraOffset();
1464 v3f old_pos = getPosition();
1466 m_matrixnode->setParent(m_smgr->getRootSceneNode());
1467 getPosRotMatrix().setTranslation(old_pos - intToFloat(camera_offset, BS));
1468 m_matrixnode->updateAbsolutePosition();
1473 parent->updateAttachments();
1474 scene::ISceneNode *parent_node = parent->getSceneNode();
1475 scene::IAnimatedMeshSceneNode *parent_animated_mesh_node =
1476 parent->getAnimatedMeshSceneNode();
1477 if (parent_animated_mesh_node && !m_attachment_bone.empty()) {
1478 parent_node = parent_animated_mesh_node->getJointNode(m_attachment_bone.c_str());
1481 if (m_matrixnode && parent_node) {
1482 m_matrixnode->setParent(parent_node);
1483 parent_node->updateAbsolutePosition();
1484 getPosRotMatrix().setTranslation(m_attachment_position);
1485 //setPitchYawRoll(getPosRotMatrix(), m_attachment_rotation);
1486 // use Irrlicht eulers instead
1487 getPosRotMatrix().setRotationDegrees(m_attachment_rotation);
1488 m_matrixnode->updateAbsolutePosition();
1493 bool GenericCAO::visualExpiryRequired(const ObjectProperties &new_) const
1495 const ObjectProperties &old = m_prop;
1496 /* Visuals do not need to be expired for:
1497 * - nametag props: handled by updateNametag()
1498 * - textures: handled by updateTextures()
1499 * - sprite props: handled by updateTexturePos()
1500 * - glow: handled by updateLight()
1501 * - any other properties that do not change appearance
1503 // Ordered to compare primitive types before std::vectors
1504 return old.backface_culling != new_.backface_culling ||
1505 old.is_visible != new_.is_visible ||
1506 old.mesh != new_.mesh ||
1507 old.use_texture_alpha != new_.use_texture_alpha ||
1508 old.visual != new_.visual ||
1509 old.visual_size != new_.visual_size ||
1510 old.wield_item != new_.wield_item ||
1511 old.colors != new_.colors;
1514 void GenericCAO::processMessage(const std::string &data)
1516 //infostream<<"GenericCAO: Got message"<<std::endl;
1517 std::istringstream is(data, std::ios::binary);
1519 u8 cmd = readU8(is);
1520 if (cmd == AO_CMD_SET_PROPERTIES) {
1521 ObjectProperties newprops;
1522 newprops.deSerialize(is);
1524 // Check what exactly changed
1525 bool expire_visuals = visualExpiryRequired(newprops);
1526 bool textures_changed = m_prop.textures != newprops.textures;
1529 m_prop = std::move(newprops);
1531 m_selection_box = m_prop.selectionbox;
1532 m_selection_box.MinEdge *= BS;
1533 m_selection_box.MaxEdge *= BS;
1535 m_tx_size.X = 1.0f / m_prop.spritediv.X;
1536 m_tx_size.Y = 1.0f / m_prop.spritediv.Y;
1538 if(!m_initial_tx_basepos_set){
1539 m_initial_tx_basepos_set = true;
1540 m_tx_basepos = m_prop.initial_sprite_basepos;
1542 if (m_is_local_player) {
1543 LocalPlayer *player = m_env->getLocalPlayer();
1544 player->makes_footstep_sound = m_prop.makes_footstep_sound;
1545 aabb3f collision_box = m_prop.collisionbox;
1546 collision_box.MinEdge *= BS;
1547 collision_box.MaxEdge *= BS;
1548 player->setCollisionbox(collision_box);
1549 player->setEyeHeight(m_prop.eye_height);
1550 player->setZoomFOV(m_prop.zoom_fov);
1553 if ((m_is_player && !m_is_local_player) && m_prop.nametag.empty())
1554 m_prop.nametag = m_name;
1556 if (expire_visuals) {
1559 infostream << "GenericCAO: properties updated but expiring visuals"
1560 << " not necessary" << std::endl;
1561 if (textures_changed) {
1562 // don't update while punch texture modifier is active
1563 if (m_reset_textures_timer < 0)
1564 updateTextures(m_current_texture_modifier);
1568 } else if (cmd == AO_CMD_UPDATE_POSITION) {
1569 // Not sent by the server if this object is an attachment.
1570 // We might however get here if the server notices the object being detached before the client.
1571 m_position = readV3F32(is);
1572 m_velocity = readV3F32(is);
1573 m_acceleration = readV3F32(is);
1574 m_rotation = readV3F32(is);
1576 m_rotation = wrapDegrees_0_360_v3f(m_rotation);
1577 bool do_interpolate = readU8(is);
1578 bool is_end_position = readU8(is);
1579 float update_interval = readF32(is);
1581 // Place us a bit higher if we're physical, to not sink into
1582 // the ground due to sucky collision detection...
1584 m_position += v3f(0,0.002,0);
1586 if(getParent() != NULL) // Just in case
1591 if(!m_prop.physical)
1592 pos_translator.update(m_position, is_end_position, update_interval);
1594 pos_translator.init(m_position);
1596 rot_translator.update(m_rotation, false, update_interval);
1598 } else if (cmd == AO_CMD_SET_TEXTURE_MOD) {
1599 std::string mod = deSerializeString(is);
1601 // immediately reset a engine issued texture modifier if a mod sends a different one
1602 if (m_reset_textures_timer > 0) {
1603 m_reset_textures_timer = -1;
1604 updateTextures(m_previous_texture_modifier);
1606 updateTextures(mod);
1607 } else if (cmd == AO_CMD_SET_SPRITE) {
1608 v2s16 p = readV2S16(is);
1609 int num_frames = readU16(is);
1610 float framelength = readF32(is);
1611 bool select_horiz_by_yawpitch = readU8(is);
1614 m_anim_num_frames = num_frames;
1615 m_anim_framelength = framelength;
1616 m_tx_select_horiz_by_yawpitch = select_horiz_by_yawpitch;
1619 } else if (cmd == AO_CMD_SET_PHYSICS_OVERRIDE) {
1620 float override_speed = readF32(is);
1621 float override_jump = readF32(is);
1622 float override_gravity = readF32(is);
1623 // these are sent inverted so we get true when the server sends nothing
1624 bool sneak = !readU8(is);
1625 bool sneak_glitch = !readU8(is);
1626 bool new_move = !readU8(is);
1629 if(m_is_local_player)
1631 LocalPlayer *player = m_env->getLocalPlayer();
1632 player->physics_override_speed = override_speed;
1633 player->physics_override_jump = override_jump;
1634 player->physics_override_gravity = override_gravity;
1635 player->physics_override_sneak = sneak;
1636 player->physics_override_sneak_glitch = sneak_glitch;
1637 player->physics_override_new_move = new_move;
1639 } else if (cmd == AO_CMD_SET_ANIMATION) {
1640 // TODO: change frames send as v2s32 value
1641 v2f range = readV2F32(is);
1642 if (!m_is_local_player) {
1643 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1644 m_animation_speed = readF32(is);
1645 m_animation_blend = readF32(is);
1646 // these are sent inverted so we get true when the server sends nothing
1647 m_animation_loop = !readU8(is);
1650 LocalPlayer *player = m_env->getLocalPlayer();
1651 if(player->last_animation == NO_ANIM)
1653 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1654 m_animation_speed = readF32(is);
1655 m_animation_blend = readF32(is);
1656 // these are sent inverted so we get true when the server sends nothing
1657 m_animation_loop = !readU8(is);
1659 // update animation only if local animations present
1660 // and received animation is unknown (except idle animation)
1661 bool is_known = false;
1662 for (int i = 1;i<4;i++)
1664 if(m_animation_range.Y == player->local_animations[i].Y)
1668 (player->local_animations[1].Y + player->local_animations[2].Y < 1))
1673 } else if (cmd == AO_CMD_SET_ANIMATION_SPEED) {
1674 m_animation_speed = readF32(is);
1675 updateAnimationSpeed();
1676 } else if (cmd == AO_CMD_SET_BONE_POSITION) {
1677 std::string bone = deSerializeString(is);
1678 v3f position = readV3F32(is);
1679 v3f rotation = readV3F32(is);
1680 m_bone_position[bone] = core::vector2d<v3f>(position, rotation);
1682 // updateBonePosition(); now called every step
1683 } else if (cmd == AO_CMD_ATTACH_TO) {
1684 u16 parent_id = readS16(is);
1685 std::string bone = deSerializeString(is);
1686 v3f position = readV3F32(is);
1687 v3f rotation = readV3F32(is);
1689 setAttachment(parent_id, bone, position, rotation);
1691 // localplayer itself can't be attached to localplayer
1692 if (!m_is_local_player)
1693 m_is_visible = !m_attached_to_local;
1694 } else if (cmd == AO_CMD_PUNCHED) {
1695 u16 result_hp = readU16(is);
1697 // Use this instead of the send damage to not interfere with prediction
1698 s32 damage = (s32)m_hp - (s32)result_hp;
1702 if (m_is_local_player)
1703 m_env->getLocalPlayer()->hp = m_hp;
1709 // TODO: Execute defined fast response
1710 // As there is no definition, make a smoke puff
1711 ClientSimpleObject *simple = createSmokePuff(
1712 m_smgr, m_env, m_position,
1713 v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
1714 m_env->addSimpleObject(simple);
1715 } else if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
1716 m_reset_textures_timer = 0.05;
1718 m_reset_textures_timer += 0.05 * damage;
1719 updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
1724 // Same as 'Server::DiePlayer'
1725 clearParentAttachment();
1726 // Same as 'ObjectRef::l_remove'
1728 clearChildAttachments();
1730 } else if (cmd == AO_CMD_UPDATE_ARMOR_GROUPS) {
1731 m_armor_groups.clear();
1732 int armor_groups_size = readU16(is);
1733 for(int i=0; i<armor_groups_size; i++)
1735 std::string name = deSerializeString(is);
1736 int rating = readS16(is);
1737 m_armor_groups[name] = rating;
1739 } else if (cmd == AO_CMD_SPAWN_INFANT) {
1740 u16 child_id = readU16(is);
1741 u8 type = readU8(is); // maybe this will be useful later
1744 addAttachmentChild(child_id);
1745 } else if (cmd == AO_CMD_OBSOLETE1) {
1746 // Don't do anything and also don't log a warning
1748 warningstream << FUNCTION_NAME
1749 << ": unknown command or outdated client \""
1750 << +cmd << "\"" << std::endl;
1754 /* \pre punchitem != NULL
1756 bool GenericCAO::directReportPunch(v3f dir, const ItemStack *punchitem,
1757 float time_from_last_punch)
1759 assert(punchitem); // pre-condition
1760 const ToolCapabilities *toolcap =
1761 &punchitem->getToolCapabilities(m_client->idef());
1762 PunchDamageResult result = getPunchDamage(
1766 time_from_last_punch);
1768 if(result.did_punch && result.damage != 0)
1770 if(result.damage < m_hp)
1772 m_hp -= result.damage;
1775 // TODO: Execute defined fast response
1776 // As there is no definition, make a smoke puff
1777 ClientSimpleObject *simple = createSmokePuff(
1778 m_smgr, m_env, m_position,
1779 v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
1780 m_env->addSimpleObject(simple);
1782 if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
1783 m_reset_textures_timer = 0.05;
1784 if (result.damage >= 2)
1785 m_reset_textures_timer += 0.05 * result.damage;
1786 updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
1793 std::string GenericCAO::debugInfoText()
1795 std::ostringstream os(std::ios::binary);
1796 os<<"GenericCAO hp="<<m_hp<<"\n";
1798 for(ItemGroupList::const_iterator i = m_armor_groups.begin();
1799 i != m_armor_groups.end(); ++i)
1801 os<<i->first<<"="<<i->second<<", ";
1808 GenericCAO proto_GenericCAO(NULL, NULL);