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 "script/scripting_client.h"
50 #include "client/minimap.h"
53 struct ToolCapabilities;
55 std::unordered_map<u16, ClientActiveObject::Factory> ClientActiveObject::m_types;
58 void SmoothTranslator<T>::init(T current)
61 val_current = current;
64 anim_time_counter = 0;
69 void SmoothTranslator<T>::update(T new_target, bool is_end_position, float update_interval)
71 aim_is_end = is_end_position;
72 val_old = val_current;
73 val_target = new_target;
74 if (update_interval > 0) {
75 anim_time = update_interval;
77 if (anim_time < 0.001 || anim_time > 1.0)
78 anim_time = anim_time_counter;
80 anim_time = anim_time * 0.9 + anim_time_counter * 0.1;
82 anim_time_counter = 0;
86 void SmoothTranslator<T>::translate(f32 dtime)
88 anim_time_counter = anim_time_counter + dtime;
89 T val_diff = val_target - val_old;
91 if (anim_time > 0.001)
92 moveratio = anim_time_counter / anim_time;
93 f32 move_end = aim_is_end ? 1.0 : 1.5;
95 // Move a bit less than should, to avoid oscillation
96 moveratio = std::min(moveratio * 0.8f, move_end);
97 val_current = val_old + val_diff * moveratio;
100 void SmoothTranslatorWrapped::translate(f32 dtime)
102 anim_time_counter = anim_time_counter + dtime;
103 f32 val_diff = std::abs(val_target - val_old);
104 if (val_diff > 180.f)
105 val_diff = 360.f - val_diff;
108 if (anim_time > 0.001)
109 moveratio = anim_time_counter / anim_time;
110 f32 move_end = aim_is_end ? 1.0 : 1.5;
112 // Move a bit less than should, to avoid oscillation
113 moveratio = std::min(moveratio * 0.8f, move_end);
114 wrappedApproachShortest(val_current, val_target,
115 val_diff * moveratio, 360.f);
118 void SmoothTranslatorWrappedv3f::translate(f32 dtime)
120 anim_time_counter = anim_time_counter + dtime;
123 val_diff_v3f.X = std::abs(val_target.X - val_old.X);
124 val_diff_v3f.Y = std::abs(val_target.Y - val_old.Y);
125 val_diff_v3f.Z = std::abs(val_target.Z - val_old.Z);
127 if (val_diff_v3f.X > 180.f)
128 val_diff_v3f.X = 360.f - val_diff_v3f.X;
130 if (val_diff_v3f.Y > 180.f)
131 val_diff_v3f.Y = 360.f - val_diff_v3f.Y;
133 if (val_diff_v3f.Z > 180.f)
134 val_diff_v3f.Z = 360.f - val_diff_v3f.Z;
137 if (anim_time > 0.001)
138 moveratio = anim_time_counter / anim_time;
139 f32 move_end = aim_is_end ? 1.0 : 1.5;
141 // Move a bit less than should, to avoid oscillation
142 moveratio = std::min(moveratio * 0.8f, move_end);
143 wrappedApproachShortest(val_current.X, val_target.X,
144 val_diff_v3f.X * moveratio, 360.f);
146 wrappedApproachShortest(val_current.Y, val_target.Y,
147 val_diff_v3f.Y * moveratio, 360.f);
149 wrappedApproachShortest(val_current.Z, val_target.Z,
150 val_diff_v3f.Z * moveratio, 360.f);
157 static void setBillboardTextureMatrix(scene::IBillboardSceneNode *bill,
158 float txs, float tys, int col, int row)
160 video::SMaterial& material = bill->getMaterial(0);
161 core::matrix4& matrix = material.getTextureMatrix(0);
162 matrix.setTextureTranslate(txs*col, tys*row);
163 matrix.setTextureScale(txs, tys);
166 // Evaluate transform chain recursively; irrlicht does not do this for us
167 static void updatePositionRecursive(scene::ISceneNode *node)
169 scene::ISceneNode *parent = node->getParent();
171 updatePositionRecursive(parent);
172 node->updateAbsolutePosition();
175 static bool logOnce(const std::ostringstream &from, std::ostream &log_to)
177 thread_local std::vector<u64> logged;
179 std::string message = from.str();
180 u64 hash = murmur_hash_64_ua(message.data(), message.length(), 0xBADBABE);
182 if (std::find(logged.begin(), logged.end(), hash) != logged.end())
184 logged.push_back(hash);
185 log_to << message << std::endl;
193 class TestCAO : public ClientActiveObject
196 TestCAO(Client *client, ClientEnvironment *env);
197 virtual ~TestCAO() = default;
199 ActiveObjectType getType() const
201 return ACTIVEOBJECT_TYPE_TEST;
204 static ClientActiveObject* create(Client *client, ClientEnvironment *env);
206 void addToScene(ITextureSource *tsrc, scene::ISceneManager *smgr);
207 void removeFromScene(bool permanent);
208 void updateLight(u32 day_night_ratio);
209 void updateNodePos();
211 void step(float dtime, ClientEnvironment *env);
213 void processMessage(const std::string &data);
215 bool getCollisionBox(aabb3f *toset) const { return false; }
217 scene::IMeshSceneNode *m_node;
222 TestCAO proto_TestCAO(NULL, NULL);
224 TestCAO::TestCAO(Client *client, ClientEnvironment *env):
225 ClientActiveObject(0, client, env),
227 m_position(v3f(0,10*BS,0))
229 ClientActiveObject::registerType(getType(), create);
232 ClientActiveObject* TestCAO::create(Client *client, ClientEnvironment *env)
234 return new TestCAO(client, env);
237 void TestCAO::addToScene(ITextureSource *tsrc, scene::ISceneManager *smgr)
242 //video::IVideoDriver* driver = smgr->getVideoDriver();
244 scene::SMesh *mesh = new scene::SMesh();
245 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
246 video::SColor c(255,255,255,255);
247 video::S3DVertex vertices[4] =
249 video::S3DVertex(-BS/2,-BS/4,0, 0,0,0, c, 0,1),
250 video::S3DVertex(BS/2,-BS/4,0, 0,0,0, c, 1,1),
251 video::S3DVertex(BS/2,BS/4,0, 0,0,0, c, 1,0),
252 video::S3DVertex(-BS/2,BS/4,0, 0,0,0, c, 0,0),
254 u16 indices[] = {0,1,2,2,3,0};
255 buf->append(vertices, 4, indices, 6);
257 buf->getMaterial().setFlag(video::EMF_LIGHTING, true); // false
258 buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
259 buf->getMaterial().setTexture(0, tsrc->getTextureForMesh("rat.png"));
260 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
261 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
262 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
264 mesh->addMeshBuffer(buf);
266 m_node = smgr->addMeshSceneNode(mesh, NULL);
271 void TestCAO::removeFromScene(bool permanent)
280 void TestCAO::updateLight(u32 day_night_ratio)
284 void TestCAO::updateNodePos()
289 m_node->setPosition(m_position);
290 //m_node->setRotation(v3f(0, 45, 0));
293 void TestCAO::step(float dtime, ClientEnvironment *env)
297 v3f rot = m_node->getRotation();
298 //infostream<<"dtime="<<dtime<<", rot.Y="<<rot.Y<<std::endl;
299 rot.Y += dtime * 180;
300 m_node->setRotation(rot);
304 void TestCAO::processMessage(const std::string &data)
306 infostream<<"TestCAO: Got data: "<<data<<std::endl;
307 std::istringstream is(data, std::ios::binary);
325 #include "clientobject.h"
327 GenericCAO::GenericCAO(Client *client, ClientEnvironment *env):
328 ClientActiveObject(0, client, env)
330 if (client == NULL) {
331 ClientActiveObject::registerType(getType(), create);
337 bool GenericCAO::getCollisionBox(aabb3f *toset) const
341 //update collision box
342 toset->MinEdge = m_prop.collisionbox.MinEdge * BS;
343 toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS;
345 toset->MinEdge += m_position;
346 toset->MaxEdge += m_position;
354 bool GenericCAO::collideWithObjects() const
356 return m_prop.collideWithObjects;
359 void GenericCAO::initialize(const std::string &data)
361 infostream<<"GenericCAO: Got init data"<<std::endl;
362 processInitData(data);
364 m_enable_shaders = g_settings->getBool("enable_shaders");
367 void GenericCAO::processInitData(const std::string &data)
369 std::istringstream is(data, std::ios::binary);
370 const u8 version = readU8(is);
373 errorstream << "GenericCAO: Unsupported init data version"
378 // PROTOCOL_VERSION >= 37
379 m_name = deSerializeString16(is);
380 m_is_player = readU8(is);
382 m_position = readV3F32(is);
383 m_rotation = readV3F32(is);
387 // Check if it's the current player
388 LocalPlayer *player = m_env->getLocalPlayer();
389 if (player && strcmp(player->getName(), m_name.c_str()) == 0) {
390 m_is_local_player = true;
391 m_is_visible = false;
392 player->setCAO(this);
396 const u8 num_messages = readU8(is);
398 for (int i = 0; i < num_messages; i++) {
399 std::string message = deSerializeString32(is);
400 processMessage(message);
403 m_rotation = wrapDegrees_0_360_v3f(m_rotation);
404 pos_translator.init(m_position);
405 rot_translator.init(m_rotation);
409 GenericCAO::~GenericCAO()
411 removeFromScene(true);
414 bool GenericCAO::getSelectionBox(aabb3f *toset) const
416 if (!m_prop.is_visible || !m_is_visible || m_is_local_player
417 || !m_prop.pointable) {
420 *toset = m_selection_box;
424 const v3f GenericCAO::getPosition() const
427 return pos_translator.val_current;
429 // Calculate real position in world based on MatrixNode
431 v3s16 camera_offset = m_env->getCameraOffset();
432 return m_matrixnode->getAbsolutePosition() +
433 intToFloat(camera_offset, BS);
439 bool GenericCAO::isImmortal() const
441 return itemgroup_get(getGroups(), "immortal");
444 scene::ISceneNode *GenericCAO::getSceneNode() const
450 if (m_animated_meshnode) {
451 return m_animated_meshnode;
454 if (m_wield_meshnode) {
455 return m_wield_meshnode;
464 scene::IAnimatedMeshSceneNode *GenericCAO::getAnimatedMeshSceneNode() const
466 return m_animated_meshnode;
469 void GenericCAO::setChildrenVisible(bool toset)
471 for (u16 cao_id : m_attachment_child_ids) {
472 GenericCAO *obj = m_env->getGenericCAO(cao_id);
474 // Check if the entity is forced to appear in first person.
475 obj->setVisible(obj->m_force_visible ? true : toset);
480 void GenericCAO::setAttachment(int parent_id, const std::string &bone,
481 v3f position, v3f rotation, bool force_visible)
483 int old_parent = m_attachment_parent_id;
484 m_attachment_parent_id = parent_id;
485 m_attachment_bone = bone;
486 m_attachment_position = position;
487 m_attachment_rotation = rotation;
488 m_force_visible = force_visible;
490 ClientActiveObject *parent = m_env->getActiveObject(parent_id);
492 if (parent_id != old_parent) {
494 m_waiting_for_reattach = 10;
495 if (auto *o = m_env->getActiveObject(old_parent))
496 o->removeAttachmentChild(m_id);
498 parent->addAttachmentChild(m_id);
503 // Forcibly show attachments if required by set_attach
504 if (m_force_visible) {
506 } else if (!m_is_local_player) {
507 // Objects attached to the local player should be hidden in first person
508 m_is_visible = !m_attached_to_local ||
509 m_client->getCamera()->getCameraMode() != CAMERA_MODE_FIRST || g_settings->getBool("freecam");
510 m_force_visible = false;
512 // Local players need to have this set,
513 // otherwise first person attachments fail.
518 void GenericCAO::getAttachment(int *parent_id, std::string *bone, v3f *position,
519 v3f *rotation, bool *force_visible) const
521 *parent_id = m_attachment_parent_id;
522 *bone = m_attachment_bone;
523 *position = m_attachment_position;
524 *rotation = m_attachment_rotation;
525 *force_visible = m_force_visible;
528 void GenericCAO::clearChildAttachments()
530 // Cannot use for-loop here: setAttachment() modifies 'm_attachment_child_ids'!
531 while (!m_attachment_child_ids.empty()) {
532 int child_id = *m_attachment_child_ids.begin();
534 if (ClientActiveObject *child = m_env->getActiveObject(child_id))
535 child->setAttachment(0, "", v3f(), v3f(), false);
537 removeAttachmentChild(child_id);
541 void GenericCAO::clearParentAttachment()
543 if (m_attachment_parent_id)
544 setAttachment(0, "", m_attachment_position, m_attachment_rotation, false);
546 setAttachment(0, "", v3f(), v3f(), false);
549 void GenericCAO::addAttachmentChild(int child_id)
551 m_attachment_child_ids.insert(child_id);
554 void GenericCAO::removeAttachmentChild(int child_id)
556 m_attachment_child_ids.erase(child_id);
559 ClientActiveObject* GenericCAO::getParent() const
561 return m_attachment_parent_id ? m_env->getActiveObject(m_attachment_parent_id) :
565 void GenericCAO::removeFromScene(bool permanent)
567 // Should be true when removing the object permanently
568 // and false when refreshing (eg: updating visuals)
569 if (m_env && permanent) {
570 // The client does not know whether this object does re-appear to
571 // a later time, thus do not clear child attachments.
573 clearParentAttachment();
576 if (auto shadow = RenderingEngine::get_shadow_renderer())
577 shadow->removeNodeFromShadowList(getSceneNode());
580 m_meshnode->remove();
582 m_meshnode = nullptr;
583 } else if (m_animated_meshnode) {
584 m_animated_meshnode->remove();
585 m_animated_meshnode->drop();
586 m_animated_meshnode = nullptr;
587 } else if (m_wield_meshnode) {
588 m_wield_meshnode->remove();
589 m_wield_meshnode->drop();
590 m_wield_meshnode = nullptr;
591 } else if (m_spritenode) {
592 m_spritenode->remove();
593 m_spritenode->drop();
594 m_spritenode = nullptr;
598 m_matrixnode->remove();
599 m_matrixnode->drop();
600 m_matrixnode = nullptr;
604 m_client->getCamera()->removeNametag(m_nametag);
608 if (m_marker && m_client->getMinimap())
609 m_client->getMinimap()->removeMarker(&m_marker);
612 void GenericCAO::addToScene(ITextureSource *tsrc, scene::ISceneManager *smgr)
616 if (getSceneNode() != NULL) {
620 m_visuals_expired = false;
622 if (!m_prop.is_visible)
625 infostream << "GenericCAO::addToScene(): " << m_prop.visual << std::endl;
627 if (m_enable_shaders) {
628 IShaderSource *shader_source = m_client->getShaderSource();
629 MaterialType material_type;
631 if (m_prop.shaded && m_prop.glow == 0)
632 material_type = (m_prop.use_texture_alpha) ?
633 TILE_MATERIAL_ALPHA : TILE_MATERIAL_BASIC;
635 material_type = (m_prop.use_texture_alpha) ?
636 TILE_MATERIAL_PLAIN_ALPHA : TILE_MATERIAL_PLAIN;
638 u32 shader_id = shader_source->getShader("object_shader", material_type, NDT_NORMAL);
639 m_material_type = shader_source->getShaderInfo(shader_id).material;
641 m_material_type = (m_prop.use_texture_alpha) ?
642 video::EMT_TRANSPARENT_ALPHA_CHANNEL : video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
645 auto grabMatrixNode = [this] {
646 m_matrixnode = m_smgr->addDummyTransformationSceneNode();
647 m_matrixnode->grab();
650 auto setSceneNodeMaterial = [this] (scene::ISceneNode *node) {
651 node->setMaterialFlag(video::EMF_LIGHTING, false);
652 node->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
653 node->setMaterialFlag(video::EMF_FOG_ENABLE, true);
654 node->setMaterialType(m_material_type);
656 if (m_enable_shaders) {
657 node->setMaterialFlag(video::EMF_GOURAUD_SHADING, false);
658 node->setMaterialFlag(video::EMF_NORMALIZE_NORMALS, true);
662 if (m_prop.visual == "sprite") {
664 m_spritenode = m_smgr->addBillboardSceneNode(
665 m_matrixnode, v2f(1, 1), v3f(0,0,0), -1);
666 m_spritenode->grab();
667 m_spritenode->setMaterialTexture(0,
668 tsrc->getTextureForMesh("no_texture.png"));
670 setSceneNodeMaterial(m_spritenode);
672 m_spritenode->setSize(v2f(m_prop.visual_size.X,
673 m_prop.visual_size.Y) * BS);
675 const float txs = 1.0 / 1;
676 const float tys = 1.0 / 1;
677 setBillboardTextureMatrix(m_spritenode,
680 } else if (m_prop.visual == "upright_sprite") {
682 scene::SMesh *mesh = new scene::SMesh();
683 double dx = BS * m_prop.visual_size.X / 2;
684 double dy = BS * m_prop.visual_size.Y / 2;
685 video::SColor c(0xFFFFFFFF);
688 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
689 video::S3DVertex vertices[4] = {
690 video::S3DVertex(-dx, -dy, 0, 0,0,1, c, 1,1),
691 video::S3DVertex( dx, -dy, 0, 0,0,1, c, 0,1),
692 video::S3DVertex( dx, dy, 0, 0,0,1, c, 0,0),
693 video::S3DVertex(-dx, dy, 0, 0,0,1, c, 1,0),
696 // Move minimal Y position to 0 (feet position)
697 for (video::S3DVertex &vertex : vertices)
700 u16 indices[] = {0,1,2,2,3,0};
701 buf->append(vertices, 4, indices, 6);
703 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
704 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
705 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
706 buf->getMaterial().MaterialType = m_material_type;
708 if (m_enable_shaders) {
709 buf->getMaterial().EmissiveColor = c;
710 buf->getMaterial().setFlag(video::EMF_GOURAUD_SHADING, false);
711 buf->getMaterial().setFlag(video::EMF_NORMALIZE_NORMALS, true);
715 mesh->addMeshBuffer(buf);
719 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
720 video::S3DVertex vertices[4] = {
721 video::S3DVertex( dx,-dy, 0, 0,0,-1, c, 1,1),
722 video::S3DVertex(-dx,-dy, 0, 0,0,-1, c, 0,1),
723 video::S3DVertex(-dx, dy, 0, 0,0,-1, c, 0,0),
724 video::S3DVertex( dx, dy, 0, 0,0,-1, c, 1,0),
727 // Move minimal Y position to 0 (feet position)
728 for (video::S3DVertex &vertex : vertices)
731 u16 indices[] = {0,1,2,2,3,0};
732 buf->append(vertices, 4, indices, 6);
734 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
735 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
736 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
737 buf->getMaterial().MaterialType = m_material_type;
739 if (m_enable_shaders) {
740 buf->getMaterial().EmissiveColor = c;
741 buf->getMaterial().setFlag(video::EMF_GOURAUD_SHADING, false);
742 buf->getMaterial().setFlag(video::EMF_NORMALIZE_NORMALS, true);
746 mesh->addMeshBuffer(buf);
749 m_meshnode = m_smgr->addMeshSceneNode(mesh, m_matrixnode);
752 } else if (m_prop.visual == "cube") {
754 scene::IMesh *mesh = createCubeMesh(v3f(BS,BS,BS));
755 m_meshnode = m_smgr->addMeshSceneNode(mesh, m_matrixnode);
759 m_meshnode->setScale(m_prop.visual_size);
760 m_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
761 m_prop.backface_culling);
763 setSceneNodeMaterial(m_meshnode);
764 } else if (m_prop.visual == "mesh") {
766 scene::IAnimatedMesh *mesh = m_client->getMesh(m_prop.mesh, true);
768 if (!checkMeshNormals(mesh)) {
769 infostream << "GenericCAO: recalculating normals for mesh "
770 << m_prop.mesh << std::endl;
771 m_smgr->getMeshManipulator()->
772 recalculateNormals(mesh, true, false);
775 m_animated_meshnode = m_smgr->addAnimatedMeshSceneNode(mesh, m_matrixnode);
776 m_animated_meshnode->grab();
777 mesh->drop(); // The scene node took hold of it
778 m_animated_meshnode->animateJoints(); // Needed for some animations
779 m_animated_meshnode->setScale(m_prop.visual_size);
781 // set vertex colors to ensure alpha is set
782 setMeshColor(m_animated_meshnode->getMesh(), video::SColor(0xFFFFFFFF));
784 setAnimatedMeshColor(m_animated_meshnode, video::SColor(0xFFFFFFFF));
786 setSceneNodeMaterial(m_animated_meshnode);
788 m_animated_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
789 m_prop.backface_culling);
791 errorstream<<"GenericCAO::addToScene(): Could not load mesh "<<m_prop.mesh<<std::endl;
792 } else if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
795 if (m_prop.wield_item.empty()) {
796 // Old format, only textures are specified.
797 infostream << "textures: " << m_prop.textures.size() << std::endl;
798 if (!m_prop.textures.empty()) {
799 infostream << "textures[0]: " << m_prop.textures[0]
801 IItemDefManager *idef = m_client->idef();
802 item = ItemStack(m_prop.textures[0], 1, 0, idef);
805 infostream << "serialized form: " << m_prop.wield_item << std::endl;
806 item.deSerialize(m_prop.wield_item, m_client->idef());
808 m_wield_meshnode = new WieldMeshSceneNode(m_smgr, -1);
809 m_wield_meshnode->setItem(item, m_client,
810 (m_prop.visual == "wielditem"));
812 m_wield_meshnode->setScale(m_prop.visual_size / 2.0f);
813 m_wield_meshnode->setColor(video::SColor(0xFFFFFFFF));
815 infostream<<"GenericCAO::addToScene(): \""<<m_prop.visual
816 <<"\" not supported"<<std::endl;
819 /* don't update while punch texture modifier is active */
820 if (m_reset_textures_timer < 0)
821 updateTextures(m_current_texture_modifier);
823 if (scene::ISceneNode *node = getSceneNode()) {
825 node->setParent(m_matrixnode);
827 if (auto shadow = RenderingEngine::get_shadow_renderer())
828 shadow->addNodeToShadowList(node);
835 updateBonePosition();
837 setNodeLight(m_last_light);
840 if (m_animated_meshnode) {
841 u32 mat_count = m_animated_meshnode->getMaterialCount();
842 if (mat_count == 0 || m_prop.textures.empty()) {
844 } else if (mat_count > m_prop.textures.size()) {
845 std::ostringstream oss;
846 oss << "GenericCAO::addToScene(): Model "
847 << m_prop.mesh << " loaded with " << mat_count
848 << " mesh buffers but only " << m_prop.textures.size()
849 << " texture(s) specifed, this is deprecated.";
850 logOnce(oss, warningstream);
852 video::ITexture *last = m_animated_meshnode->getMaterial(0).TextureLayer[0].Texture;
853 for (u32 i = 1; i < mat_count; i++) {
854 auto &layer = m_animated_meshnode->getMaterial(i).TextureLayer[0];
856 layer.Texture = last;
857 last = layer.Texture;
862 if (m_client->modsLoaded() && m_client->getScript()->on_object_add(m_id)) {
863 removeFromScene(false);
867 if (m_client->modsLoaded())
868 m_client->getScript()->on_object_properties_change(m_id);
871 void GenericCAO::updateLight(u32 day_night_ratio)
876 u16 light_at_pos = 0;
877 u8 light_at_pos_intensity = 0;
881 u16 npos = getLightPosition(pos);
882 for (u16 i = 0; i < npos; i++) {
884 MapNode n = m_env->getMap().getNode(pos[i], &this_ok);
886 u16 this_light = getInteriorLight(n, 0, m_client->ndef());
887 u8 this_light_intensity = MYMAX(this_light & 0xFF, (this_light >> 8) && 0xFF);
888 if (this_light_intensity > light_at_pos_intensity) {
889 light_at_pos = this_light;
890 light_at_pos_intensity = this_light_intensity;
896 light_at_pos = LIGHT_SUN;
898 video::SColor light = encode_light(light_at_pos, m_glow);
899 if (!m_enable_shaders)
900 final_color_blend(&light, light_at_pos, day_night_ratio);
902 if (g_settings->getBool("fullbright"))
903 light = video::SColor(0xFFFFFFFF);
905 if (light != m_last_light) {
906 m_last_light = light;
911 void GenericCAO::setNodeLight(const video::SColor &light_color)
913 if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
914 if (m_wield_meshnode)
915 m_wield_meshnode->setNodeLightColor(light_color);
919 if (m_enable_shaders) {
920 if (m_prop.visual == "upright_sprite") {
924 scene::IMesh *mesh = m_meshnode->getMesh();
925 for (u32 i = 0; i < mesh->getMeshBufferCount(); ++i) {
926 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
927 buf->getMaterial().EmissiveColor = light_color;
930 scene::ISceneNode *node = getSceneNode();
934 for (u32 i = 0; i < node->getMaterialCount(); ++i) {
935 video::SMaterial &material = node->getMaterial(i);
936 material.EmissiveColor = light_color;
941 setMeshColor(m_meshnode->getMesh(), light_color);
942 } else if (m_animated_meshnode) {
943 setAnimatedMeshColor(m_animated_meshnode, light_color);
944 } else if (m_spritenode) {
945 m_spritenode->setColor(light_color);
950 u16 GenericCAO::getLightPosition(v3s16 *pos)
952 const auto &box = m_prop.collisionbox;
953 pos[0] = floatToInt(m_position + box.MinEdge * BS, BS);
954 pos[1] = floatToInt(m_position + box.MaxEdge * BS, BS);
956 // Skip center pos if it falls into the same node as Min or MaxEdge
957 if ((box.MaxEdge - box.MinEdge).getLengthSQ() < 3.0f)
959 pos[2] = floatToInt(m_position + box.getCenter() * BS, BS);
963 void GenericCAO::updateMarker()
965 if (!m_client->getMinimap())
968 if (!m_prop.show_on_minimap) {
970 m_client->getMinimap()->removeMarker(&m_marker);
977 scene::ISceneNode *node = getSceneNode();
980 m_marker = m_client->getMinimap()->addMarker(node);
983 void GenericCAO::updateNametag()
985 //if (m_is_local_player && ! g_settings->getBool("freecam")) // No nametag for local player
988 if (m_prop.nametag.empty() || m_prop.nametag_color.getAlpha() == 0) {
991 m_client->getCamera()->removeNametag(m_nametag);
997 scene::ISceneNode *node = getSceneNode();
1002 pos.Y = m_prop.selectionbox.MaxEdge.Y + 0.3f;
1005 m_nametag = m_client->getCamera()->addNametag(node,
1006 m_prop.nametag, m_prop.nametag_color,
1007 m_prop.nametag_bgcolor, pos, nametag_images);
1010 m_nametag->text = m_prop.nametag;
1011 m_nametag->textcolor = m_prop.nametag_color;
1012 m_nametag->bgcolor = m_prop.nametag_bgcolor;
1013 m_nametag->pos = pos;
1014 m_nametag->setImages(nametag_images);
1018 void GenericCAO::updateNodePos()
1020 if (getParent() != NULL)
1023 scene::ISceneNode *node = getSceneNode();
1026 v3s16 camera_offset = m_env->getCameraOffset();
1027 v3f pos = pos_translator.val_current -
1028 intToFloat(camera_offset, BS);
1029 getPosRotMatrix().setTranslation(pos);
1030 if (node != m_spritenode) { // rotate if not a sprite
1031 v3f rot = m_is_local_player ? -m_rotation : -rot_translator.val_current;
1032 setPitchYawRoll(getPosRotMatrix(), rot);
1037 void GenericCAO::step(float dtime, ClientEnvironment *env)
1039 // Handle model animations and update positions instantly to prevent lags
1040 if (m_is_local_player) {
1041 LocalPlayer *player = m_env->getLocalPlayer();
1042 m_position = player->getLegitPosition();
1043 pos_translator.val_current = m_position;
1044 if (! g_settings->getBool("freecam")) {
1045 m_rotation.Y = wrapDegrees_0_360(player->getYaw());
1046 rot_translator.val_current = m_rotation;
1050 int old_anim = player->last_animation;
1051 float old_anim_speed = player->last_animation_speed;
1052 m_velocity = v3f(0,0,0);
1053 m_acceleration = v3f(0,0,0);
1054 const PlayerControl &controls = player->getPlayerControl();
1055 f32 new_speed = player->local_animation_speed;
1057 bool walking = false;
1058 if (controls.movement_speed > 0.001f && ! g_settings->getBool("freecam")) {
1059 new_speed *= controls.movement_speed;
1063 v2s32 new_anim = v2s32(0,0);
1064 bool allow_update = false;
1066 // increase speed if using fast or flying fast
1067 if(((g_settings->getBool("fast_move") &&
1068 m_client->checkLocalPrivilege("fast")) &&
1070 (!player->touching_ground &&
1071 g_settings->getBool("free_move") &&
1072 m_client->checkLocalPrivilege("fly")))) || g_settings->getBool("freecam"))
1074 // slowdown speed if sneaking
1075 if (controls.sneak && walking && ! g_settings->getBool("no_slow"))
1078 if (walking && (controls.dig || controls.place)) {
1079 new_anim = player->local_animations[3];
1080 player->last_animation = WD_ANIM;
1081 } else if (walking) {
1082 new_anim = player->local_animations[1];
1083 player->last_animation = WALK_ANIM;
1084 } else if (controls.dig || controls.place) {
1085 new_anim = player->local_animations[2];
1086 player->last_animation = DIG_ANIM;
1089 // Apply animations if input detected and not attached
1090 // or set idle animation
1091 if ((new_anim.X + new_anim.Y) > 0 && !getParent()) {
1092 allow_update = true;
1093 m_animation_range = new_anim;
1094 m_animation_speed = new_speed;
1095 player->last_animation_speed = m_animation_speed;
1097 player->last_animation = NO_ANIM;
1099 if (old_anim != NO_ANIM) {
1100 m_animation_range = player->local_animations[0];
1105 // Update local player animations
1106 if ((player->last_animation != old_anim ||
1107 m_animation_speed != old_anim_speed) &&
1108 player->last_animation != NO_ANIM && allow_update)
1114 if (m_visuals_expired && m_smgr) {
1115 m_visuals_expired = false;
1117 // Attachments, part 1: All attached objects must be unparented first,
1118 // or Irrlicht causes a segmentation fault
1119 for (u16 cao_id : m_attachment_child_ids) {
1120 ClientActiveObject *obj = m_env->getActiveObject(cao_id);
1122 scene::ISceneNode *child_node = obj->getSceneNode();
1123 // The node's parent is always an IDummyTraformationSceneNode,
1124 // so we need to reparent that one instead.
1126 child_node->getParent()->setParent(m_smgr->getRootSceneNode());
1130 removeFromScene(false);
1131 addToScene(m_client->tsrc(), m_smgr);
1133 // Attachments, part 2: Now that the parent has been refreshed, put its attachments back
1134 for (u16 cao_id : m_attachment_child_ids) {
1135 ClientActiveObject *obj = m_env->getActiveObject(cao_id);
1137 obj->updateAttachments();
1141 // Make sure m_is_visible is always applied
1142 scene::ISceneNode *node = getSceneNode();
1144 node->setVisible(m_is_visible);
1146 if(getParent() != NULL) // Attachments should be glued to their parent by Irrlicht
1148 // Set these for later
1149 m_position = getPosition();
1150 m_velocity = v3f(0,0,0);
1151 m_acceleration = v3f(0,0,0);
1152 pos_translator.val_current = m_position;
1153 pos_translator.val_target = m_position;
1155 rot_translator.translate(dtime);
1156 v3f lastpos = pos_translator.val_current;
1160 aabb3f box = m_prop.collisionbox;
1163 collisionMoveResult moveresult;
1164 f32 pos_max_d = BS*0.125; // Distance per iteration
1165 v3f p_pos = m_position;
1166 v3f p_velocity = m_velocity;
1167 moveresult = collisionMoveSimple(env,env->getGameDef(),
1168 pos_max_d, box, m_prop.stepheight, dtime,
1169 &p_pos, &p_velocity, m_acceleration,
1170 this, m_prop.collideWithObjects);
1173 m_velocity = p_velocity;
1175 bool is_end_position = moveresult.collides;
1176 pos_translator.update(m_position, is_end_position, dtime);
1178 m_position += dtime * m_velocity + 0.5 * dtime * dtime * m_acceleration;
1179 m_velocity += dtime * m_acceleration;
1180 pos_translator.update(m_position, pos_translator.aim_is_end,
1181 pos_translator.anim_time);
1183 pos_translator.translate(dtime);
1186 float moved = lastpos.getDistanceFrom(pos_translator.val_current);
1187 m_step_distance_counter += moved;
1188 if (m_step_distance_counter > 1.5f * BS) {
1189 m_step_distance_counter = 0.0f;
1190 if (!m_is_local_player && m_prop.makes_footstep_sound) {
1191 const NodeDefManager *ndef = m_client->ndef();
1192 v3s16 p = floatToInt(getPosition() +
1193 v3f(0.0f, (m_prop.collisionbox.MinEdge.Y - 0.5f) * BS, 0.0f), BS);
1194 MapNode n = m_env->getMap().getNode(p);
1195 SimpleSoundSpec spec = ndef->get(n).sound_footstep;
1196 // Reduce footstep gain, as non-local-player footsteps are
1199 m_client->sound()->playSoundAt(spec, false, getPosition());
1204 m_anim_timer += dtime;
1205 if(m_anim_timer >= m_anim_framelength)
1207 m_anim_timer -= m_anim_framelength;
1209 if(m_anim_frame >= m_anim_num_frames)
1215 if(m_reset_textures_timer >= 0)
1217 m_reset_textures_timer -= dtime;
1218 if(m_reset_textures_timer <= 0) {
1219 m_reset_textures_timer = -1;
1220 updateTextures(m_previous_texture_modifier);
1224 if (!getParent() && node && fabs(m_prop.automatic_rotate) > 0.001f) {
1225 // This is the child node's rotation. It is only used for automatic_rotate.
1226 v3f local_rot = node->getRotation();
1227 local_rot.Y = modulo360f(local_rot.Y - dtime * core::RADTODEG *
1228 m_prop.automatic_rotate);
1229 node->setRotation(local_rot);
1232 if (!getParent() && m_prop.automatic_face_movement_dir &&
1233 (fabs(m_velocity.Z) > 0.001f || fabs(m_velocity.X) > 0.001f)) {
1234 float target_yaw = atan2(m_velocity.Z, m_velocity.X) * 180 / M_PI
1235 + m_prop.automatic_face_movement_dir_offset;
1236 float max_rotation_per_sec =
1237 m_prop.automatic_face_movement_max_rotation_per_sec;
1239 if (max_rotation_per_sec > 0) {
1240 wrappedApproachShortest(m_rotation.Y, target_yaw,
1241 dtime * max_rotation_per_sec, 360.f);
1243 // Negative values of max_rotation_per_sec mean disabled.
1244 m_rotation.Y = target_yaw;
1247 rot_translator.val_current = m_rotation;
1251 if (m_animated_meshnode) {
1252 // Everything must be updated; the whole transform
1253 // chain as well as the animated mesh node.
1254 // Otherwise, bone attachments would be relative to
1255 // a position that's one frame old.
1257 updatePositionRecursive(m_matrixnode);
1258 m_animated_meshnode->updateAbsolutePosition();
1259 m_animated_meshnode->animateJoints();
1260 updateBonePosition();
1264 void GenericCAO::updateTexturePos()
1268 scene::ICameraSceneNode* camera =
1269 m_spritenode->getSceneManager()->getActiveCamera();
1272 v3f cam_to_entity = m_spritenode->getAbsolutePosition()
1273 - camera->getAbsolutePosition();
1274 cam_to_entity.normalize();
1276 int row = m_tx_basepos.Y;
1277 int col = m_tx_basepos.X;
1279 // Yawpitch goes rightwards
1280 if (m_tx_select_horiz_by_yawpitch) {
1281 if (cam_to_entity.Y > 0.75)
1283 else if (cam_to_entity.Y < -0.75)
1287 atan2(cam_to_entity.Z, cam_to_entity.X) / M_PI * 180.;
1288 float dir = mob_dir - m_rotation.Y;
1289 dir = wrapDegrees_180(dir);
1290 if (std::fabs(wrapDegrees_180(dir - 0)) <= 45.1f)
1292 else if(std::fabs(wrapDegrees_180(dir - 90)) <= 45.1f)
1294 else if(std::fabs(wrapDegrees_180(dir - 180)) <= 45.1f)
1296 else if(std::fabs(wrapDegrees_180(dir + 90)) <= 45.1f)
1303 // Animation goes downwards
1304 row += m_anim_frame;
1306 float txs = m_tx_size.X;
1307 float tys = m_tx_size.Y;
1308 setBillboardTextureMatrix(m_spritenode, txs, tys, col, row);
1311 else if (m_meshnode) {
1312 if (m_prop.visual == "upright_sprite") {
1313 int row = m_tx_basepos.Y;
1314 int col = m_tx_basepos.X;
1316 // Animation goes downwards
1317 row += m_anim_frame;
1319 const auto &tx = m_tx_size;
1320 v2f t[4] = { // cf. vertices in GenericCAO::addToScene()
1321 tx * v2f(col+1, row+1),
1322 tx * v2f(col, row+1),
1324 tx * v2f(col+1, row),
1326 auto mesh = m_meshnode->getMesh();
1327 setMeshBufferTextureCoords(mesh->getMeshBuffer(0), t, 4);
1328 setMeshBufferTextureCoords(mesh->getMeshBuffer(1), t, 4);
1333 // Do not pass by reference, see header.
1334 void GenericCAO::updateTextures(std::string mod)
1336 ITextureSource *tsrc = m_client->tsrc();
1338 bool use_trilinear_filter = g_settings->getBool("trilinear_filter");
1339 bool use_bilinear_filter = g_settings->getBool("bilinear_filter");
1340 bool use_anisotropic_filter = g_settings->getBool("anisotropic_filter");
1342 m_previous_texture_modifier = m_current_texture_modifier;
1343 m_current_texture_modifier = mod;
1344 m_glow = m_prop.glow;
1346 video::ITexture *shadow_texture = nullptr;
1347 if (auto shadow = RenderingEngine::get_shadow_renderer())
1348 shadow_texture = shadow->get_texture();
1350 const u32 TEXTURE_LAYER_SHADOW = 3;
1353 if (m_prop.visual == "sprite") {
1354 std::string texturestring = "no_texture.png";
1355 if (!m_prop.textures.empty())
1356 texturestring = m_prop.textures[0];
1357 texturestring += mod;
1358 m_spritenode->getMaterial(0).MaterialType = m_material_type;
1359 m_spritenode->getMaterial(0).MaterialTypeParam = 0.5f;
1360 m_spritenode->setMaterialTexture(0,
1361 tsrc->getTextureForMesh(texturestring));
1362 m_spritenode->setMaterialTexture(TEXTURE_LAYER_SHADOW, shadow_texture);
1364 // This allows setting per-material colors. However, until a real lighting
1365 // system is added, the code below will have no effect. Once MineTest
1366 // has directional lighting, it should work automatically.
1367 if (!m_prop.colors.empty()) {
1368 m_spritenode->getMaterial(0).AmbientColor = m_prop.colors[0];
1369 m_spritenode->getMaterial(0).DiffuseColor = m_prop.colors[0];
1370 m_spritenode->getMaterial(0).SpecularColor = m_prop.colors[0];
1373 m_spritenode->getMaterial(0).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1374 m_spritenode->getMaterial(0).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1375 m_spritenode->getMaterial(0).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1379 else if (m_animated_meshnode) {
1380 if (m_prop.visual == "mesh") {
1381 for (u32 i = 0; i < m_prop.textures.size() &&
1382 i < m_animated_meshnode->getMaterialCount(); ++i) {
1383 std::string texturestring = m_prop.textures[i];
1384 if (texturestring.empty())
1385 continue; // Empty texture string means don't modify that material
1386 texturestring += mod;
1387 video::ITexture* texture = tsrc->getTextureForMesh(texturestring);
1389 errorstream<<"GenericCAO::updateTextures(): Could not load texture "<<texturestring<<std::endl;
1393 // Set material flags and texture
1394 video::SMaterial& material = m_animated_meshnode->getMaterial(i);
1395 material.MaterialType = m_material_type;
1396 material.MaterialTypeParam = 0.5f;
1397 material.TextureLayer[0].Texture = texture;
1398 material.TextureLayer[TEXTURE_LAYER_SHADOW].Texture = shadow_texture;
1399 material.setFlag(video::EMF_LIGHTING, true);
1400 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1401 material.setFlag(video::EMF_BACK_FACE_CULLING, m_prop.backface_culling);
1403 // don't filter low-res textures, makes them look blurry
1404 // player models have a res of 64
1405 const core::dimension2d<u32> &size = texture->getOriginalSize();
1406 const u32 res = std::min(size.Height, size.Width);
1407 use_trilinear_filter &= res > 64;
1408 use_bilinear_filter &= res > 64;
1410 m_animated_meshnode->getMaterial(i)
1411 .setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1412 m_animated_meshnode->getMaterial(i)
1413 .setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1414 m_animated_meshnode->getMaterial(i)
1415 .setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1417 for (u32 i = 0; i < m_prop.colors.size() &&
1418 i < m_animated_meshnode->getMaterialCount(); ++i)
1420 // This allows setting per-material colors. However, until a real lighting
1421 // system is added, the code below will have no effect. Once MineTest
1422 // has directional lighting, it should work automatically.
1423 m_animated_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1424 m_animated_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1425 m_animated_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1430 else if (m_meshnode) {
1431 if(m_prop.visual == "cube")
1433 for (u32 i = 0; i < 6; ++i)
1435 std::string texturestring = "no_texture.png";
1436 if(m_prop.textures.size() > i)
1437 texturestring = m_prop.textures[i];
1438 texturestring += mod;
1441 // Set material flags and texture
1442 video::SMaterial& material = m_meshnode->getMaterial(i);
1443 material.MaterialType = m_material_type;
1444 material.MaterialTypeParam = 0.5f;
1445 material.setFlag(video::EMF_LIGHTING, false);
1446 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1447 material.setTexture(0,
1448 tsrc->getTextureForMesh(texturestring));
1449 material.setTexture(TEXTURE_LAYER_SHADOW, shadow_texture);
1450 material.getTextureMatrix(0).makeIdentity();
1452 // This allows setting per-material colors. However, until a real lighting
1453 // system is added, the code below will have no effect. Once MineTest
1454 // has directional lighting, it should work automatically.
1455 if(m_prop.colors.size() > i)
1457 m_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1458 m_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1459 m_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1462 m_meshnode->getMaterial(i).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1463 m_meshnode->getMaterial(i).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1464 m_meshnode->getMaterial(i).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1466 } else if (m_prop.visual == "upright_sprite") {
1467 scene::IMesh *mesh = m_meshnode->getMesh();
1469 std::string tname = "no_texture.png";
1470 if (!m_prop.textures.empty())
1471 tname = m_prop.textures[0];
1473 auto& material = m_meshnode->getMaterial(0);
1474 material.setTexture(0,
1475 tsrc->getTextureForMesh(tname));
1476 material.setTexture(TEXTURE_LAYER_SHADOW, shadow_texture);
1478 // This allows setting per-material colors. However, until a real lighting
1479 // system is added, the code below will have no effect. Once MineTest
1480 // has directional lighting, it should work automatically.
1481 if(!m_prop.colors.empty()) {
1482 material.AmbientColor = m_prop.colors[0];
1483 material.DiffuseColor = m_prop.colors[0];
1484 material.SpecularColor = m_prop.colors[0];
1487 material.setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1488 material.setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1489 material.setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1492 std::string tname = "no_texture.png";
1493 if (m_prop.textures.size() >= 2)
1494 tname = m_prop.textures[1];
1495 else if (!m_prop.textures.empty())
1496 tname = m_prop.textures[0];
1498 auto& material = m_meshnode->getMaterial(1);
1499 material.setTexture(0,
1500 tsrc->getTextureForMesh(tname));
1501 material.setTexture(TEXTURE_LAYER_SHADOW, shadow_texture);
1503 // This allows setting per-material colors. However, until a real lighting
1504 // system is added, the code below will have no effect. Once MineTest
1505 // has directional lighting, it should work automatically.
1506 if (m_prop.colors.size() >= 2) {
1507 material.AmbientColor = m_prop.colors[1];
1508 material.DiffuseColor = m_prop.colors[1];
1509 material.SpecularColor = m_prop.colors[1];
1510 } else if (!m_prop.colors.empty()) {
1511 material.AmbientColor = m_prop.colors[0];
1512 material.DiffuseColor = m_prop.colors[0];
1513 material.SpecularColor = m_prop.colors[0];
1516 material.setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1517 material.setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1518 material.setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1520 // Set mesh color (only if lighting is disabled)
1521 if (!m_prop.colors.empty() && m_glow < 0)
1522 setMeshColor(mesh, m_prop.colors[0]);
1525 // Prevent showing the player after changing texture
1526 if (m_is_local_player)
1527 updateMeshCulling();
1530 void GenericCAO::updateAnimation()
1532 if (!m_animated_meshnode)
1535 if (m_animated_meshnode->getStartFrame() != m_animation_range.X ||
1536 m_animated_meshnode->getEndFrame() != m_animation_range.Y)
1537 m_animated_meshnode->setFrameLoop(m_animation_range.X, m_animation_range.Y);
1538 if (m_animated_meshnode->getAnimationSpeed() != m_animation_speed)
1539 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1540 m_animated_meshnode->setTransitionTime(m_animation_blend);
1541 if (m_animated_meshnode->getLoopMode() != m_animation_loop)
1542 m_animated_meshnode->setLoopMode(m_animation_loop);
1545 void GenericCAO::updateAnimationSpeed()
1547 if (!m_animated_meshnode)
1550 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1553 void GenericCAO::updateBonePosition()
1555 if (m_bone_position.empty() || !m_animated_meshnode)
1558 m_animated_meshnode->setJointMode(scene::EJUOR_CONTROL); // To write positions to the mesh on render
1559 for (auto &it : m_bone_position) {
1560 std::string bone_name = it.first;
1561 scene::IBoneSceneNode* bone = m_animated_meshnode->getJointNode(bone_name.c_str());
1563 bone->setPosition(it.second.X);
1564 bone->setRotation(it.second.Y);
1568 // search through bones to find mistakenly rotated bones due to bug in Irrlicht
1569 for (u32 i = 0; i < m_animated_meshnode->getJointCount(); ++i) {
1570 scene::IBoneSceneNode *bone = m_animated_meshnode->getJointNode(i);
1574 //If bone is manually positioned there is no need to perform the bug check
1576 for (auto &it : m_bone_position) {
1577 if (it.first == bone->getName()) {
1585 // Workaround for Irrlicht bug
1586 // We check each bone to see if it has been rotated ~180deg from its expected position due to a bug in Irricht
1587 // when using EJUOR_CONTROL joint control. If the bug is detected we update the bone to the proper position
1588 // and update the bones transformation.
1589 v3f bone_rot = bone->getRelativeTransformation().getRotationDegrees();
1590 float offset = fabsf(bone_rot.X - bone->getRotation().X);
1591 if (offset > 179.9f && offset < 180.1f) {
1592 bone->setRotation(bone_rot);
1593 bone->updateAbsolutePosition();
1596 // The following is needed for set_bone_pos to propagate to
1597 // attached objects correctly.
1598 // Irrlicht ought to do this, but doesn't when using EJUOR_CONTROL.
1599 for (u32 i = 0; i < m_animated_meshnode->getJointCount(); ++i) {
1600 auto bone = m_animated_meshnode->getJointNode(i);
1601 // Look for the root bone.
1602 if (bone && bone->getParent() == m_animated_meshnode) {
1603 // Update entire skeleton.
1604 bone->updateAbsolutePositionOfAllChildren();
1610 void GenericCAO::updateAttachments()
1612 ClientActiveObject *parent = getParent();
1614 m_attached_to_local = parent && parent->isLocalPlayer();
1617 Following cases exist:
1618 m_attachment_parent_id == 0 && !parent
1619 This object is not attached
1620 m_attachment_parent_id != 0 && parent
1621 This object is attached
1622 m_attachment_parent_id != 0 && !parent
1623 This object will be attached as soon the parent is known
1624 m_attachment_parent_id == 0 && parent
1628 if (!parent) { // Detach or don't attach
1630 v3s16 camera_offset = m_env->getCameraOffset();
1631 v3f old_pos = getPosition();
1633 m_matrixnode->setParent(m_smgr->getRootSceneNode());
1634 getPosRotMatrix().setTranslation(old_pos - intToFloat(camera_offset, BS));
1635 m_matrixnode->updateAbsolutePosition();
1640 parent->updateAttachments();
1641 scene::ISceneNode *parent_node = parent->getSceneNode();
1642 scene::IAnimatedMeshSceneNode *parent_animated_mesh_node =
1643 parent->getAnimatedMeshSceneNode();
1644 if (parent_animated_mesh_node && !m_attachment_bone.empty()) {
1645 parent_node = parent_animated_mesh_node->getJointNode(m_attachment_bone.c_str());
1648 if (m_matrixnode && parent_node) {
1649 m_matrixnode->setParent(parent_node);
1650 parent_node->updateAbsolutePosition();
1651 getPosRotMatrix().setTranslation(m_attachment_position);
1652 //setPitchYawRoll(getPosRotMatrix(), m_attachment_rotation);
1653 // use Irrlicht eulers instead
1654 getPosRotMatrix().setRotationDegrees(m_attachment_rotation);
1655 m_matrixnode->updateAbsolutePosition();
1660 bool GenericCAO::visualExpiryRequired(const ObjectProperties &new_) const
1662 const ObjectProperties &old = m_prop;
1663 /* Visuals do not need to be expired for:
1664 * - nametag props: handled by updateNametag()
1665 * - textures: handled by updateTextures()
1666 * - sprite props: handled by updateTexturePos()
1667 * - glow: handled by updateLight()
1668 * - any other properties that do not change appearance
1671 bool uses_legacy_texture = new_.wield_item.empty() &&
1672 (new_.visual == "wielditem" || new_.visual == "item");
1673 // Ordered to compare primitive types before std::vectors
1674 return old.backface_culling != new_.backface_culling ||
1675 old.is_visible != new_.is_visible ||
1676 old.mesh != new_.mesh ||
1677 old.shaded != new_.shaded ||
1678 old.use_texture_alpha != new_.use_texture_alpha ||
1679 old.visual != new_.visual ||
1680 old.visual_size != new_.visual_size ||
1681 old.wield_item != new_.wield_item ||
1682 old.colors != new_.colors ||
1683 (uses_legacy_texture && old.textures != new_.textures);
1686 void GenericCAO::setProperties(ObjectProperties newprops)
1688 // Check what exactly changed
1689 bool expire_visuals = visualExpiryRequired(newprops);
1690 bool textures_changed = m_prop.textures != newprops.textures;
1693 m_prop = std::move(newprops);
1695 m_selection_box = m_prop.selectionbox;
1696 m_selection_box.MinEdge *= BS;
1697 m_selection_box.MaxEdge *= BS;
1699 m_tx_size.X = 1.0f / m_prop.spritediv.X;
1700 m_tx_size.Y = 1.0f / m_prop.spritediv.Y;
1702 if(!m_initial_tx_basepos_set){
1703 m_initial_tx_basepos_set = true;
1704 m_tx_basepos = m_prop.initial_sprite_basepos;
1706 if (m_is_local_player) {
1707 LocalPlayer *player = m_env->getLocalPlayer();
1708 player->makes_footstep_sound = m_prop.makes_footstep_sound;
1709 aabb3f collision_box = m_prop.collisionbox;
1710 collision_box.MinEdge *= BS;
1711 collision_box.MaxEdge *= BS;
1712 player->setCollisionbox(collision_box);
1713 player->setEyeHeight(m_prop.eye_height);
1714 player->setZoomFOV(m_prop.zoom_fov);
1717 if ((m_is_player && !m_is_local_player) && m_prop.nametag.empty())
1718 m_prop.nametag = m_name;
1719 if (m_is_local_player)
1720 m_prop.show_on_minimap = false;
1722 if (expire_visuals) {
1725 infostream << "GenericCAO: properties updated but expiring visuals"
1726 << " not necessary" << std::endl;
1727 if (textures_changed) {
1728 // don't update while punch texture modifier is active
1729 if (m_reset_textures_timer < 0)
1730 updateTextures(m_current_texture_modifier);
1737 void GenericCAO::processMessage(const std::string &data)
1739 //infostream<<"GenericCAO: Got message"<<std::endl;
1740 std::istringstream is(data, std::ios::binary);
1742 u8 cmd = readU8(is);
1743 if (cmd == AO_CMD_SET_PROPERTIES) {
1744 ObjectProperties newprops;
1745 newprops.show_on_minimap = m_is_player; // default
1747 newprops.deSerialize(is);
1748 setProperties(newprops);
1751 if (m_client->modsLoaded())
1752 m_client->getScript()->on_object_properties_change(m_id);
1754 } else if (cmd == AO_CMD_UPDATE_POSITION) {
1755 // Not sent by the server if this object is an attachment.
1756 // We might however get here if the server notices the object being detached before the client.
1757 m_position = readV3F32(is);
1758 m_velocity = readV3F32(is);
1759 m_acceleration = readV3F32(is);
1760 m_rotation = readV3F32(is);
1762 m_rotation = wrapDegrees_0_360_v3f(m_rotation);
1763 bool do_interpolate = readU8(is);
1764 bool is_end_position = readU8(is);
1765 float update_interval = readF32(is);
1767 // Place us a bit higher if we're physical, to not sink into
1768 // the ground due to sucky collision detection...
1770 m_position += v3f(0,0.002,0);
1772 if(getParent() != NULL) // Just in case
1777 if(!m_prop.physical)
1778 pos_translator.update(m_position, is_end_position, update_interval);
1780 pos_translator.init(m_position);
1782 rot_translator.update(m_rotation, false, update_interval);
1784 } else if (cmd == AO_CMD_SET_TEXTURE_MOD) {
1785 std::string mod = deSerializeString16(is);
1787 // immediately reset a engine issued texture modifier if a mod sends a different one
1788 if (m_reset_textures_timer > 0) {
1789 m_reset_textures_timer = -1;
1790 updateTextures(m_previous_texture_modifier);
1792 updateTextures(mod);
1793 } else if (cmd == AO_CMD_SET_SPRITE) {
1794 v2s16 p = readV2S16(is);
1795 int num_frames = readU16(is);
1796 float framelength = readF32(is);
1797 bool select_horiz_by_yawpitch = readU8(is);
1800 m_anim_num_frames = num_frames;
1802 m_anim_framelength = framelength;
1803 m_tx_select_horiz_by_yawpitch = select_horiz_by_yawpitch;
1806 } else if (cmd == AO_CMD_SET_PHYSICS_OVERRIDE) {
1807 float override_speed = readF32(is);
1808 float override_jump = readF32(is);
1809 float override_gravity = readF32(is);
1810 // these are sent inverted so we get true when the server sends nothing
1811 bool sneak = !readU8(is);
1812 bool sneak_glitch = !readU8(is);
1813 bool new_move = !readU8(is);
1816 if(m_is_local_player)
1818 Client *client = m_env->getGameDef();
1820 if (client->modsLoaded() && client->getScript()->on_recieve_physics_override(override_speed, override_jump, override_gravity, sneak, sneak_glitch, new_move))
1823 LocalPlayer *player = m_env->getLocalPlayer();
1824 player->physics_override_speed = override_speed;
1825 player->physics_override_jump = override_jump;
1826 player->physics_override_gravity = override_gravity;
1827 player->physics_override_sneak = sneak;
1828 player->physics_override_sneak_glitch = sneak_glitch;
1829 player->physics_override_new_move = new_move;
1831 } else if (cmd == AO_CMD_SET_ANIMATION) {
1832 // TODO: change frames send as v2s32 value
1833 v2f range = readV2F32(is);
1834 if (!m_is_local_player) {
1835 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1836 m_animation_speed = readF32(is);
1837 m_animation_blend = readF32(is);
1838 // these are sent inverted so we get true when the server sends nothing
1839 m_animation_loop = !readU8(is);
1842 LocalPlayer *player = m_env->getLocalPlayer();
1843 if(player->last_animation == NO_ANIM)
1845 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1846 m_animation_speed = readF32(is);
1847 m_animation_blend = readF32(is);
1848 // these are sent inverted so we get true when the server sends nothing
1849 m_animation_loop = !readU8(is);
1851 // update animation only if local animations present
1852 // and received animation is unknown (except idle animation)
1853 bool is_known = false;
1854 for (int i = 1;i<4;i++)
1856 if(m_animation_range.Y == player->local_animations[i].Y)
1860 (player->local_animations[1].Y + player->local_animations[2].Y < 1))
1864 // FIXME: ^ This code is trash. It's also broken.
1866 } else if (cmd == AO_CMD_SET_ANIMATION_SPEED) {
1867 m_animation_speed = readF32(is);
1868 updateAnimationSpeed();
1869 } else if (cmd == AO_CMD_SET_BONE_POSITION) {
1870 std::string bone = deSerializeString16(is);
1871 v3f position = readV3F32(is);
1872 v3f rotation = readV3F32(is);
1873 m_bone_position[bone] = core::vector2d<v3f>(position, rotation);
1875 // updateBonePosition(); now called every step
1876 } else if (cmd == AO_CMD_ATTACH_TO) {
1877 u16 parent_id = readS16(is);
1878 std::string bone = deSerializeString16(is);
1879 v3f position = readV3F32(is);
1880 v3f rotation = readV3F32(is);
1881 bool force_visible = readU8(is); // Returns false for EOF
1883 setAttachment(parent_id, bone, position, rotation, force_visible);
1884 } else if (cmd == AO_CMD_PUNCHED) {
1885 u16 result_hp = readU16(is);
1887 // Use this instead of the send damage to not interfere with prediction
1888 s32 damage = (s32)m_hp - (s32)result_hp;
1892 if (m_is_local_player)
1893 m_env->getLocalPlayer()->hp = m_hp;
1899 // TODO: Execute defined fast response
1900 // As there is no definition, make a smoke puff
1901 ClientSimpleObject *simple = createSmokePuff(
1902 m_smgr, m_env, m_position,
1903 v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
1904 m_env->addSimpleObject(simple);
1905 } else if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
1906 m_reset_textures_timer = 0.05;
1908 m_reset_textures_timer += 0.05 * damage;
1909 // Cap damage overlay to 1 second
1910 m_reset_textures_timer = std::min(m_reset_textures_timer, 1.0f);
1911 updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
1916 // Same as 'Server::DiePlayer'
1917 clearParentAttachment();
1918 // Same as 'ObjectRef::l_remove'
1920 clearChildAttachments();
1922 if (m_client->modsLoaded())
1923 m_client->getScript()->on_object_hp_change(m_id);
1925 } else if (cmd == AO_CMD_UPDATE_ARMOR_GROUPS) {
1926 m_armor_groups.clear();
1927 int armor_groups_size = readU16(is);
1928 for(int i=0; i<armor_groups_size; i++)
1930 std::string name = deSerializeString16(is);
1931 int rating = readS16(is);
1932 m_armor_groups[name] = rating;
1934 } else if (cmd == AO_CMD_SPAWN_INFANT) {
1935 u16 child_id = readU16(is);
1936 u8 type = readU8(is); // maybe this will be useful later
1939 addAttachmentChild(child_id);
1940 } else if (cmd == AO_CMD_OBSOLETE1) {
1941 // Don't do anything and also don't log a warning
1943 warningstream << FUNCTION_NAME
1944 << ": unknown command or outdated client \""
1945 << +cmd << "\"" << std::endl;
1949 /* \pre punchitem != NULL
1951 bool GenericCAO::directReportPunch(v3f dir, const ItemStack *punchitem,
1952 float time_from_last_punch)
1954 assert(punchitem); // pre-condition
1955 const ToolCapabilities *toolcap =
1956 &punchitem->getToolCapabilities(m_client->idef());
1957 PunchDamageResult result = getPunchDamage(
1961 time_from_last_punch,
1964 if(result.did_punch && result.damage != 0)
1966 if(result.damage < m_hp)
1968 m_hp -= result.damage;
1971 // TODO: Execute defined fast response
1972 // As there is no definition, make a smoke puff
1973 ClientSimpleObject *simple = createSmokePuff(
1974 m_smgr, m_env, m_position,
1975 v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
1976 m_env->addSimpleObject(simple);
1978 if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
1979 m_reset_textures_timer = 0.05;
1980 if (result.damage >= 2)
1981 m_reset_textures_timer += 0.05 * result.damage;
1982 // Cap damage overlay to 1 second
1983 m_reset_textures_timer = std::min(m_reset_textures_timer, 1.0f);
1984 updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
1991 std::string GenericCAO::debugInfoText()
1993 std::ostringstream os(std::ios::binary);
1994 os<<"GenericCAO hp="<<m_hp<<"\n";
1996 for(ItemGroupList::const_iterator i = m_armor_groups.begin();
1997 i != m_armor_groups.end(); ++i)
1999 os<<i->first<<"="<<i->second<<", ";
2005 void GenericCAO::updateMeshCulling()
2007 if (!m_is_local_player)
2010 const bool hidden = m_client->getCamera()->getCameraMode() == CAMERA_MODE_FIRST && ! g_settings->getBool("freecam");
2012 scene::ISceneNode *node = getSceneNode();
2017 if (m_prop.visual == "upright_sprite") {
2018 // upright sprite has no backface culling
2019 node->setMaterialFlag(video::EMF_FRONT_FACE_CULLING, hidden);
2024 // Hide the mesh by culling both front and
2025 // back faces. Serious hackyness but it works for our
2026 // purposes. This also preserves the skeletal armature.
2027 node->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
2029 node->setMaterialFlag(video::EMF_FRONT_FACE_CULLING,
2032 // Restore mesh visibility.
2033 node->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
2034 m_prop.backface_culling);
2035 node->setMaterialFlag(video::EMF_FRONT_FACE_CULLING,
2041 GenericCAO proto_GenericCAO(NULL, NULL);