3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "content_cao.h"
21 #include <IBillboardSceneNode.h>
22 #include <ICameraSceneNode.h>
23 #include <ITextSceneNode.h>
24 #include <IMeshManipulator.h>
25 #include <IAnimatedMeshSceneNode.h>
26 #include "client/client.h"
27 #include "client/renderingengine.h"
28 #include "client/sound.h"
29 #include "client/tile.h"
30 #include "util/basic_macros.h"
31 #include "util/numeric.h" // For IntervalLimiter & setPitchYawRoll
32 #include "util/serialize.h"
33 #include "camera.h" // CameraModes
34 #include "collision.h"
35 #include "content_cso.h"
36 #include "environment.h"
38 #include "localplayer.h"
42 #include "serialization.h" // For decompressZlib
46 #include "wieldmesh.h"
49 #include "client/shader.h"
50 #include "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();
179 class TestCAO : public ClientActiveObject
182 TestCAO(Client *client, ClientEnvironment *env);
183 virtual ~TestCAO() = default;
185 ActiveObjectType getType() const
187 return ACTIVEOBJECT_TYPE_TEST;
190 static ClientActiveObject* create(Client *client, ClientEnvironment *env);
192 void addToScene(ITextureSource *tsrc);
193 void removeFromScene(bool permanent);
194 void updateLight(u32 day_night_ratio);
195 void updateNodePos();
197 void step(float dtime, ClientEnvironment *env);
199 void processMessage(const std::string &data);
201 bool getCollisionBox(aabb3f *toset) const { return false; }
203 scene::IMeshSceneNode *m_node;
208 TestCAO proto_TestCAO(NULL, NULL);
210 TestCAO::TestCAO(Client *client, ClientEnvironment *env):
211 ClientActiveObject(0, client, env),
213 m_position(v3f(0,10*BS,0))
215 ClientActiveObject::registerType(getType(), create);
218 ClientActiveObject* TestCAO::create(Client *client, ClientEnvironment *env)
220 return new TestCAO(client, env);
223 void TestCAO::addToScene(ITextureSource *tsrc)
228 //video::IVideoDriver* driver = smgr->getVideoDriver();
230 scene::SMesh *mesh = new scene::SMesh();
231 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
232 video::SColor c(255,255,255,255);
233 video::S3DVertex vertices[4] =
235 video::S3DVertex(-BS/2,-BS/4,0, 0,0,0, c, 0,1),
236 video::S3DVertex(BS/2,-BS/4,0, 0,0,0, c, 1,1),
237 video::S3DVertex(BS/2,BS/4,0, 0,0,0, c, 1,0),
238 video::S3DVertex(-BS/2,BS/4,0, 0,0,0, c, 0,0),
240 u16 indices[] = {0,1,2,2,3,0};
241 buf->append(vertices, 4, indices, 6);
243 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
244 buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
245 buf->getMaterial().setTexture(0, tsrc->getTextureForMesh("rat.png"));
246 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
247 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
248 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
250 mesh->addMeshBuffer(buf);
252 m_node = RenderingEngine::get_scene_manager()->addMeshSceneNode(mesh, NULL);
257 void TestCAO::removeFromScene(bool permanent)
266 void TestCAO::updateLight(u32 day_night_ratio)
270 void TestCAO::updateNodePos()
275 m_node->setPosition(m_position);
276 //m_node->setRotation(v3f(0, 45, 0));
279 void TestCAO::step(float dtime, ClientEnvironment *env)
283 v3f rot = m_node->getRotation();
284 //infostream<<"dtime="<<dtime<<", rot.Y="<<rot.Y<<std::endl;
285 rot.Y += dtime * 180;
286 m_node->setRotation(rot);
290 void TestCAO::processMessage(const std::string &data)
292 infostream<<"TestCAO: Got data: "<<data<<std::endl;
293 std::istringstream is(data, std::ios::binary);
311 #include "clientobject.h"
313 GenericCAO::GenericCAO(Client *client, ClientEnvironment *env):
314 ClientActiveObject(0, client, env)
316 if (client == NULL) {
317 ClientActiveObject::registerType(getType(), create);
323 bool GenericCAO::getCollisionBox(aabb3f *toset) const
327 //update collision box
328 toset->MinEdge = m_prop.collisionbox.MinEdge * BS;
329 toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS;
331 toset->MinEdge += m_position;
332 toset->MaxEdge += m_position;
340 bool GenericCAO::collideWithObjects() const
342 return m_prop.collideWithObjects;
345 void GenericCAO::initialize(const std::string &data)
347 infostream<<"GenericCAO: Got init data"<<std::endl;
348 processInitData(data);
351 // Check if it's the current player
352 LocalPlayer *player = m_env->getLocalPlayer();
353 if (player && strcmp(player->getName(), m_name.c_str()) == 0) {
354 m_is_local_player = true;
355 m_is_visible = false;
356 player->setCAO(this);
358 m_prop.show_on_minimap = false;
362 m_enable_shaders = g_settings->getBool("enable_shaders");
365 void GenericCAO::processInitData(const std::string &data)
367 std::istringstream is(data, std::ios::binary);
368 const u8 version = readU8(is);
371 errorstream << "GenericCAO: Unsupported init data version"
376 // PROTOCOL_VERSION >= 37
377 m_name = deSerializeString16(is);
378 m_is_player = readU8(is);
380 m_position = readV3F32(is);
381 m_rotation = readV3F32(is);
384 const u8 num_messages = readU8(is);
386 for (int i = 0; i < num_messages; i++) {
387 std::string message = deSerializeString32(is);
388 processMessage(message);
391 m_rotation = wrapDegrees_0_360_v3f(m_rotation);
392 pos_translator.init(m_position);
393 rot_translator.init(m_rotation);
397 GenericCAO::~GenericCAO()
399 removeFromScene(true);
402 bool GenericCAO::getSelectionBox(aabb3f *toset) const
404 if (!m_prop.is_visible || !m_is_visible || m_is_local_player
405 || !m_prop.pointable) {
408 *toset = m_selection_box;
412 const v3f GenericCAO::getPosition() const
415 return pos_translator.val_current;
417 // Calculate real position in world based on MatrixNode
419 v3s16 camera_offset = m_env->getCameraOffset();
420 return m_matrixnode->getAbsolutePosition() +
421 intToFloat(camera_offset, BS);
427 const bool GenericCAO::isImmortal()
429 return itemgroup_get(getGroups(), "immortal");
432 scene::ISceneNode *GenericCAO::getSceneNode() const
438 if (m_animated_meshnode) {
439 return m_animated_meshnode;
442 if (m_wield_meshnode) {
443 return m_wield_meshnode;
452 scene::IAnimatedMeshSceneNode *GenericCAO::getAnimatedMeshSceneNode() const
454 return m_animated_meshnode;
457 void GenericCAO::setChildrenVisible(bool toset)
459 for (u16 cao_id : m_attachment_child_ids) {
460 GenericCAO *obj = m_env->getGenericCAO(cao_id);
462 // Check if the entity is forced to appear in first person.
463 obj->setVisible(obj->isForcedVisible() ? true : toset);
468 void GenericCAO::setAttachment(int parent_id, const std::string &bone, v3f position, v3f rotation)
470 int old_parent = m_attachment_parent_id;
471 m_attachment_parent_id = parent_id;
472 m_attachment_bone = bone;
473 m_attachment_position = position;
474 m_attachment_rotation = rotation;
476 ClientActiveObject *parent = m_env->getActiveObject(parent_id);
478 if (parent_id != old_parent) {
479 if (auto *o = m_env->getActiveObject(old_parent))
480 o->removeAttachmentChild(m_id);
482 parent->addAttachmentChild(m_id);
487 void GenericCAO::getAttachment(int *parent_id, std::string *bone, v3f *position,
490 *parent_id = m_attachment_parent_id;
491 *bone = m_attachment_bone;
492 *position = m_attachment_position;
493 *rotation = m_attachment_rotation;
496 void GenericCAO::clearChildAttachments()
498 // Cannot use for-loop here: setAttachment() modifies 'm_attachment_child_ids'!
499 while (!m_attachment_child_ids.empty()) {
500 int child_id = *m_attachment_child_ids.begin();
502 if (ClientActiveObject *child = m_env->getActiveObject(child_id))
503 child->setAttachment(0, "", v3f(), v3f(), false);
505 removeAttachmentChild(child_id);
509 void GenericCAO::clearParentAttachment()
511 if (m_attachment_parent_id)
512 setAttachment(0, "", m_attachment_position, m_attachment_rotation);
514 setAttachment(0, "", v3f(), v3f());
517 void GenericCAO::addAttachmentChild(int child_id)
519 m_attachment_child_ids.insert(child_id);
522 void GenericCAO::removeAttachmentChild(int child_id)
524 m_attachment_child_ids.erase(child_id);
527 ClientActiveObject* GenericCAO::getParent() const
529 return m_attachment_parent_id ? m_env->getActiveObject(m_attachment_parent_id) :
533 void GenericCAO::removeFromScene(bool permanent)
535 // Should be true when removing the object permanently
536 // and false when refreshing (eg: updating visuals)
537 if (m_env && permanent) {
538 // The client does not know whether this object does re-appear to
539 // a later time, thus do not clear child attachments.
541 clearParentAttachment();
545 m_meshnode->remove();
547 m_meshnode = nullptr;
548 } else if (m_animated_meshnode) {
549 m_animated_meshnode->remove();
550 m_animated_meshnode->drop();
551 m_animated_meshnode = nullptr;
552 } else if (m_wield_meshnode) {
553 m_wield_meshnode->remove();
554 m_wield_meshnode->drop();
555 m_wield_meshnode = nullptr;
556 } else if (m_spritenode) {
557 m_spritenode->remove();
558 m_spritenode->drop();
559 m_spritenode = nullptr;
563 m_matrixnode->remove();
564 m_matrixnode->drop();
565 m_matrixnode = nullptr;
569 m_client->getCamera()->removeNametag(m_nametag);
573 if (m_marker && m_client->getMinimap())
574 m_client->getMinimap()->removeMarker(&m_marker);
577 void GenericCAO::addToScene(ITextureSource *tsrc)
579 m_smgr = RenderingEngine::get_scene_manager();
581 if (getSceneNode() != NULL) {
585 m_visuals_expired = false;
587 if (!m_prop.is_visible)
590 infostream << "GenericCAO::addToScene(): " << m_prop.visual << std::endl;
592 if (m_enable_shaders) {
593 IShaderSource *shader_source = m_client->getShaderSource();
594 MaterialType material_type;
596 if (m_prop.shaded && m_prop.glow == 0)
597 material_type = (m_prop.use_texture_alpha) ?
598 TILE_MATERIAL_ALPHA : TILE_MATERIAL_BASIC;
600 material_type = (m_prop.use_texture_alpha) ?
601 TILE_MATERIAL_PLAIN_ALPHA : TILE_MATERIAL_PLAIN;
603 u32 shader_id = shader_source->getShader("object_shader", material_type, NDT_NORMAL);
604 m_material_type = shader_source->getShaderInfo(shader_id).material;
606 m_material_type = (m_prop.use_texture_alpha) ?
607 video::EMT_TRANSPARENT_ALPHA_CHANNEL : video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
610 auto grabMatrixNode = [this] {
611 m_matrixnode = RenderingEngine::get_scene_manager()->
612 addDummyTransformationSceneNode();
613 m_matrixnode->grab();
616 auto setSceneNodeMaterial = [this] (scene::ISceneNode *node) {
617 node->setMaterialFlag(video::EMF_LIGHTING, false);
618 node->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
619 node->setMaterialFlag(video::EMF_FOG_ENABLE, true);
620 node->setMaterialType(m_material_type);
622 if (m_enable_shaders) {
623 node->setMaterialFlag(video::EMF_GOURAUD_SHADING, false);
624 node->setMaterialFlag(video::EMF_NORMALIZE_NORMALS, true);
628 if (m_prop.visual == "sprite") {
630 m_spritenode = RenderingEngine::get_scene_manager()->addBillboardSceneNode(
631 m_matrixnode, v2f(1, 1), v3f(0,0,0), -1);
632 m_spritenode->grab();
633 m_spritenode->setMaterialTexture(0,
634 tsrc->getTextureForMesh("unknown_node.png"));
636 setSceneNodeMaterial(m_spritenode);
638 m_spritenode->setSize(v2f(m_prop.visual_size.X,
639 m_prop.visual_size.Y) * BS);
641 const float txs = 1.0 / 1;
642 const float tys = 1.0 / 1;
643 setBillboardTextureMatrix(m_spritenode,
646 } else if (m_prop.visual == "upright_sprite") {
648 scene::SMesh *mesh = new scene::SMesh();
649 double dx = BS * m_prop.visual_size.X / 2;
650 double dy = BS * m_prop.visual_size.Y / 2;
651 video::SColor c(0xFFFFFFFF);
654 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
655 video::S3DVertex vertices[4] = {
656 video::S3DVertex(-dx, -dy, 0, 0,0,1, c, 1,1),
657 video::S3DVertex( dx, -dy, 0, 0,0,1, c, 0,1),
658 video::S3DVertex( dx, dy, 0, 0,0,1, c, 0,0),
659 video::S3DVertex(-dx, dy, 0, 0,0,1, c, 1,0),
662 // Move minimal Y position to 0 (feet position)
663 for (video::S3DVertex &vertex : vertices)
666 u16 indices[] = {0,1,2,2,3,0};
667 buf->append(vertices, 4, indices, 6);
669 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
670 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
671 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
672 buf->getMaterial().MaterialType = m_material_type;
674 if (m_enable_shaders) {
675 buf->getMaterial().EmissiveColor = c;
676 buf->getMaterial().setFlag(video::EMF_GOURAUD_SHADING, false);
677 buf->getMaterial().setFlag(video::EMF_NORMALIZE_NORMALS, true);
681 mesh->addMeshBuffer(buf);
685 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
686 video::S3DVertex vertices[4] = {
687 video::S3DVertex( dx,-dy, 0, 0,0,-1, c, 1,1),
688 video::S3DVertex(-dx,-dy, 0, 0,0,-1, c, 0,1),
689 video::S3DVertex(-dx, dy, 0, 0,0,-1, c, 0,0),
690 video::S3DVertex( dx, dy, 0, 0,0,-1, c, 1,0),
693 // Move minimal Y position to 0 (feet position)
694 for (video::S3DVertex &vertex : vertices)
697 u16 indices[] = {0,1,2,2,3,0};
698 buf->append(vertices, 4, indices, 6);
700 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
701 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
702 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
703 buf->getMaterial().MaterialType = m_material_type;
705 if (m_enable_shaders) {
706 buf->getMaterial().EmissiveColor = c;
707 buf->getMaterial().setFlag(video::EMF_GOURAUD_SHADING, false);
708 buf->getMaterial().setFlag(video::EMF_NORMALIZE_NORMALS, true);
712 mesh->addMeshBuffer(buf);
715 m_meshnode = RenderingEngine::get_scene_manager()->
716 addMeshSceneNode(mesh, m_matrixnode);
719 // Set it to use the materials of the meshbuffers directly.
720 // This is needed for changing the texture in the future
721 m_meshnode->setReadOnlyMaterials(true);
722 } else if (m_prop.visual == "cube") {
724 scene::IMesh *mesh = createCubeMesh(v3f(BS,BS,BS));
725 m_meshnode = RenderingEngine::get_scene_manager()->
726 addMeshSceneNode(mesh, m_matrixnode);
730 m_meshnode->setScale(m_prop.visual_size);
731 m_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
732 m_prop.backface_culling);
734 setSceneNodeMaterial(m_meshnode);
735 } else if (m_prop.visual == "mesh") {
737 scene::IAnimatedMesh *mesh = m_client->getMesh(m_prop.mesh, true);
739 m_animated_meshnode = RenderingEngine::get_scene_manager()->
740 addAnimatedMeshSceneNode(mesh, m_matrixnode);
741 m_animated_meshnode->grab();
742 mesh->drop(); // The scene node took hold of it
744 if (!checkMeshNormals(mesh)) {
745 infostream << "GenericCAO: recalculating normals for mesh "
746 << m_prop.mesh << std::endl;
747 m_smgr->getMeshManipulator()->
748 recalculateNormals(mesh, true, false);
751 m_animated_meshnode->animateJoints(); // Needed for some animations
752 m_animated_meshnode->setScale(m_prop.visual_size);
754 // set vertex colors to ensure alpha is set
755 setMeshColor(m_animated_meshnode->getMesh(), video::SColor(0xFFFFFFFF));
757 setAnimatedMeshColor(m_animated_meshnode, video::SColor(0xFFFFFFFF));
759 setSceneNodeMaterial(m_animated_meshnode);
761 m_animated_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
762 m_prop.backface_culling);
764 errorstream<<"GenericCAO::addToScene(): Could not load mesh "<<m_prop.mesh<<std::endl;
765 } else if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
768 if (m_prop.wield_item.empty()) {
769 // Old format, only textures are specified.
770 infostream << "textures: " << m_prop.textures.size() << std::endl;
771 if (!m_prop.textures.empty()) {
772 infostream << "textures[0]: " << m_prop.textures[0]
774 IItemDefManager *idef = m_client->idef();
775 item = ItemStack(m_prop.textures[0], 1, 0, idef);
778 infostream << "serialized form: " << m_prop.wield_item << std::endl;
779 item.deSerialize(m_prop.wield_item, m_client->idef());
781 m_wield_meshnode = new WieldMeshSceneNode(
782 RenderingEngine::get_scene_manager(), -1);
783 m_wield_meshnode->setItem(item, m_client,
784 (m_prop.visual == "wielditem"));
786 m_wield_meshnode->setScale(m_prop.visual_size / 2.0f);
787 m_wield_meshnode->setColor(video::SColor(0xFFFFFFFF));
789 infostream<<"GenericCAO::addToScene(): \""<<m_prop.visual
790 <<"\" not supported"<<std::endl;
793 /* don't update while punch texture modifier is active */
794 if (m_reset_textures_timer < 0)
795 updateTextures(m_current_texture_modifier);
797 scene::ISceneNode *node = getSceneNode();
799 if (node && m_matrixnode)
800 node->setParent(m_matrixnode);
806 updateBonePosition();
808 setNodeLight(m_last_light);
812 void GenericCAO::updateLight(u32 day_night_ratio)
821 u16 npos = getLightPosition(pos);
822 for (u16 i = 0; i < npos; i++) {
824 MapNode n = m_env->getMap().getNode(pos[i], &this_ok);
826 u8 this_light = n.getLightBlend(day_night_ratio, m_client->ndef());
827 light_at_pos = MYMAX(light_at_pos, this_light);
832 light_at_pos = blend_light(day_night_ratio, LIGHT_SUN, 0);
834 u8 light = decode_light(light_at_pos + m_glow);
835 if (light != m_last_light) {
836 m_last_light = light;
841 void GenericCAO::setNodeLight(u8 light)
843 video::SColor color(255, light, light, light);
845 if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
846 if (m_wield_meshnode)
847 m_wield_meshnode->setNodeLightColor(color);
851 if (m_enable_shaders) {
852 if (m_prop.visual == "upright_sprite") {
856 scene::IMesh *mesh = m_meshnode->getMesh();
857 for (u32 i = 0; i < mesh->getMeshBufferCount(); ++i) {
858 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
859 buf->getMaterial().EmissiveColor = color;
862 scene::ISceneNode *node = getSceneNode();
866 for (u32 i = 0; i < node->getMaterialCount(); ++i) {
867 video::SMaterial &material = node->getMaterial(i);
868 material.EmissiveColor = color;
873 setMeshColor(m_meshnode->getMesh(), color);
874 } else if (m_animated_meshnode) {
875 setAnimatedMeshColor(m_animated_meshnode, color);
876 } else if (m_spritenode) {
877 m_spritenode->setColor(color);
882 u16 GenericCAO::getLightPosition(v3s16 *pos)
884 const auto &box = m_prop.collisionbox;
885 pos[0] = floatToInt(m_position + box.MinEdge * BS, BS);
886 pos[1] = floatToInt(m_position + box.MaxEdge * BS, BS);
888 // Skip center pos if it falls into the same node as Min or MaxEdge
889 if ((box.MaxEdge - box.MinEdge).getLengthSQ() < 3.0f)
891 pos[2] = floatToInt(m_position + box.getCenter() * BS, BS);
895 void GenericCAO::updateMarker()
897 if (!m_prop.show_on_minimap) {
899 m_client->getMinimap()->removeMarker(&m_marker);
906 scene::ISceneNode *node = getSceneNode();
909 m_marker = m_client->getMinimap()->addMarker(node);
912 void GenericCAO::updateNametag()
914 if (m_is_local_player) // No nametag for local player
917 if (m_prop.nametag.empty()) {
920 m_client->getCamera()->removeNametag(m_nametag);
926 scene::ISceneNode *node = getSceneNode();
931 pos.Y = m_prop.selectionbox.MaxEdge.Y + 0.3f;
934 m_nametag = m_client->getCamera()->addNametag(node,
935 m_prop.nametag, m_prop.nametag_color, pos);
938 m_nametag->nametag_text = m_prop.nametag;
939 m_nametag->nametag_color = m_prop.nametag_color;
940 m_nametag->nametag_pos = pos;
944 void GenericCAO::updateNodePos()
946 if (getParent() != NULL)
949 scene::ISceneNode *node = getSceneNode();
952 v3s16 camera_offset = m_env->getCameraOffset();
953 v3f pos = pos_translator.val_current -
954 intToFloat(camera_offset, BS);
955 getPosRotMatrix().setTranslation(pos);
956 if (node != m_spritenode) { // rotate if not a sprite
957 v3f rot = m_is_local_player ? -m_rotation : -rot_translator.val_current;
958 setPitchYawRoll(getPosRotMatrix(), rot);
963 void GenericCAO::step(float dtime, ClientEnvironment *env)
965 // Handle model animations and update positions instantly to prevent lags
966 if (m_is_local_player) {
967 LocalPlayer *player = m_env->getLocalPlayer();
968 m_position = player->getPosition();
969 pos_translator.val_current = m_position;
970 m_rotation.Y = wrapDegrees_0_360(player->getYaw());
971 rot_translator.val_current = m_rotation;
974 int old_anim = player->last_animation;
975 float old_anim_speed = player->last_animation_speed;
976 m_velocity = v3f(0,0,0);
977 m_acceleration = v3f(0,0,0);
978 const PlayerControl &controls = player->getPlayerControl();
980 bool walking = false;
981 if (controls.up || controls.down || controls.left || controls.right ||
982 controls.forw_move_joystick_axis != 0.f ||
983 controls.sidew_move_joystick_axis != 0.f)
986 f32 new_speed = player->local_animation_speed;
987 v2s32 new_anim = v2s32(0,0);
988 bool allow_update = false;
990 // increase speed if using fast or flying fast
991 if((g_settings->getBool("fast_move") &&
992 m_client->checkLocalPrivilege("fast")) &&
994 (!player->touching_ground &&
995 g_settings->getBool("free_move") &&
996 m_client->checkLocalPrivilege("fly"))))
998 // slowdown speed if sneeking
999 if (controls.sneak && walking)
1002 if (walking && (controls.dig || controls.place)) {
1003 new_anim = player->local_animations[3];
1004 player->last_animation = WD_ANIM;
1005 } else if (walking) {
1006 new_anim = player->local_animations[1];
1007 player->last_animation = WALK_ANIM;
1008 } else if (controls.dig || controls.place) {
1009 new_anim = player->local_animations[2];
1010 player->last_animation = DIG_ANIM;
1013 // Apply animations if input detected and not attached
1014 // or set idle animation
1015 if ((new_anim.X + new_anim.Y) > 0 && !getParent()) {
1016 allow_update = true;
1017 m_animation_range = new_anim;
1018 m_animation_speed = new_speed;
1019 player->last_animation_speed = m_animation_speed;
1021 player->last_animation = NO_ANIM;
1023 if (old_anim != NO_ANIM) {
1024 m_animation_range = player->local_animations[0];
1029 // Update local player animations
1030 if ((player->last_animation != old_anim ||
1031 m_animation_speed != old_anim_speed) &&
1032 player->last_animation != NO_ANIM && allow_update)
1038 if (m_visuals_expired && m_smgr) {
1039 m_visuals_expired = false;
1041 // Attachments, part 1: All attached objects must be unparented first,
1042 // or Irrlicht causes a segmentation fault
1043 for (u16 cao_id : m_attachment_child_ids) {
1044 ClientActiveObject *obj = m_env->getActiveObject(cao_id);
1046 scene::ISceneNode *child_node = obj->getSceneNode();
1047 // The node's parent is always an IDummyTraformationSceneNode,
1048 // so we need to reparent that one instead.
1050 child_node->getParent()->setParent(m_smgr->getRootSceneNode());
1054 removeFromScene(false);
1055 addToScene(m_client->tsrc());
1057 // Attachments, part 2: Now that the parent has been refreshed, put its attachments back
1058 for (u16 cao_id : m_attachment_child_ids) {
1059 ClientActiveObject *obj = m_env->getActiveObject(cao_id);
1061 obj->updateAttachments();
1065 // Make sure m_is_visible is always applied
1066 scene::ISceneNode *node = getSceneNode();
1068 node->setVisible(m_is_visible);
1070 if(getParent() != NULL) // Attachments should be glued to their parent by Irrlicht
1072 // Set these for later
1073 m_position = getPosition();
1074 m_velocity = v3f(0,0,0);
1075 m_acceleration = v3f(0,0,0);
1076 pos_translator.val_current = m_position;
1077 pos_translator.val_target = m_position;
1079 rot_translator.translate(dtime);
1080 v3f lastpos = pos_translator.val_current;
1084 aabb3f box = m_prop.collisionbox;
1087 collisionMoveResult moveresult;
1088 f32 pos_max_d = BS*0.125; // Distance per iteration
1089 v3f p_pos = m_position;
1090 v3f p_velocity = m_velocity;
1091 moveresult = collisionMoveSimple(env,env->getGameDef(),
1092 pos_max_d, box, m_prop.stepheight, dtime,
1093 &p_pos, &p_velocity, m_acceleration,
1094 this, m_prop.collideWithObjects);
1097 m_velocity = p_velocity;
1099 bool is_end_position = moveresult.collides;
1100 pos_translator.update(m_position, is_end_position, dtime);
1102 m_position += dtime * m_velocity + 0.5 * dtime * dtime * m_acceleration;
1103 m_velocity += dtime * m_acceleration;
1104 pos_translator.update(m_position, pos_translator.aim_is_end,
1105 pos_translator.anim_time);
1107 pos_translator.translate(dtime);
1110 float moved = lastpos.getDistanceFrom(pos_translator.val_current);
1111 m_step_distance_counter += moved;
1112 if (m_step_distance_counter > 1.5f * BS) {
1113 m_step_distance_counter = 0.0f;
1114 if (!m_is_local_player && m_prop.makes_footstep_sound) {
1115 const NodeDefManager *ndef = m_client->ndef();
1116 v3s16 p = floatToInt(getPosition() +
1117 v3f(0.0f, (m_prop.collisionbox.MinEdge.Y - 0.5f) * BS, 0.0f), BS);
1118 MapNode n = m_env->getMap().getNode(p);
1119 SimpleSoundSpec spec = ndef->get(n).sound_footstep;
1120 // Reduce footstep gain, as non-local-player footsteps are
1123 m_client->sound()->playSoundAt(spec, false, getPosition());
1128 m_anim_timer += dtime;
1129 if(m_anim_timer >= m_anim_framelength)
1131 m_anim_timer -= m_anim_framelength;
1133 if(m_anim_frame >= m_anim_num_frames)
1139 if(m_reset_textures_timer >= 0)
1141 m_reset_textures_timer -= dtime;
1142 if(m_reset_textures_timer <= 0) {
1143 m_reset_textures_timer = -1;
1144 updateTextures(m_previous_texture_modifier);
1148 if (!getParent() && std::fabs(m_prop.automatic_rotate) > 0.001) {
1149 // This is the child node's rotation. It is only used for automatic_rotate.
1150 v3f local_rot = node->getRotation();
1151 local_rot.Y = modulo360f(local_rot.Y - dtime * core::RADTODEG *
1152 m_prop.automatic_rotate);
1153 node->setRotation(local_rot);
1156 if (!getParent() && m_prop.automatic_face_movement_dir &&
1157 (fabs(m_velocity.Z) > 0.001 || fabs(m_velocity.X) > 0.001)) {
1158 float target_yaw = atan2(m_velocity.Z, m_velocity.X) * 180 / M_PI
1159 + m_prop.automatic_face_movement_dir_offset;
1160 float max_rotation_per_sec =
1161 m_prop.automatic_face_movement_max_rotation_per_sec;
1163 if (max_rotation_per_sec > 0) {
1164 wrappedApproachShortest(m_rotation.Y, target_yaw,
1165 dtime * max_rotation_per_sec, 360.f);
1167 // Negative values of max_rotation_per_sec mean disabled.
1168 m_rotation.Y = target_yaw;
1171 rot_translator.val_current = m_rotation;
1175 if (m_animated_meshnode) {
1176 // Everything must be updated; the whole transform
1177 // chain as well as the animated mesh node.
1178 // Otherwise, bone attachments would be relative to
1179 // a position that's one frame old.
1181 updatePositionRecursive(m_matrixnode);
1182 m_animated_meshnode->updateAbsolutePosition();
1183 m_animated_meshnode->animateJoints();
1184 updateBonePosition();
1188 void GenericCAO::updateTexturePos()
1192 scene::ICameraSceneNode* camera =
1193 m_spritenode->getSceneManager()->getActiveCamera();
1196 v3f cam_to_entity = m_spritenode->getAbsolutePosition()
1197 - camera->getAbsolutePosition();
1198 cam_to_entity.normalize();
1200 int row = m_tx_basepos.Y;
1201 int col = m_tx_basepos.X;
1203 // Yawpitch goes rightwards
1204 if (m_tx_select_horiz_by_yawpitch) {
1205 if (cam_to_entity.Y > 0.75)
1207 else if (cam_to_entity.Y < -0.75)
1211 atan2(cam_to_entity.Z, cam_to_entity.X) / M_PI * 180.;
1212 float dir = mob_dir - m_rotation.Y;
1213 dir = wrapDegrees_180(dir);
1214 if (std::fabs(wrapDegrees_180(dir - 0)) <= 45.1f)
1216 else if(std::fabs(wrapDegrees_180(dir - 90)) <= 45.1f)
1218 else if(std::fabs(wrapDegrees_180(dir - 180)) <= 45.1f)
1220 else if(std::fabs(wrapDegrees_180(dir + 90)) <= 45.1f)
1227 // Animation goes downwards
1228 row += m_anim_frame;
1230 float txs = m_tx_size.X;
1231 float tys = m_tx_size.Y;
1232 setBillboardTextureMatrix(m_spritenode, txs, tys, col, row);
1235 else if (m_meshnode) {
1236 if (m_prop.visual == "upright_sprite") {
1237 int row = m_tx_basepos.Y;
1238 int col = m_tx_basepos.X;
1240 // Animation goes downwards
1241 row += m_anim_frame;
1243 const auto &tx = m_tx_size;
1244 v2f t[4] = { // cf. vertices in GenericCAO::addToScene()
1245 tx * v2f(col+1, row+1),
1246 tx * v2f(col, row+1),
1248 tx * v2f(col+1, row),
1250 auto mesh = m_meshnode->getMesh();
1251 setMeshBufferTextureCoords(mesh->getMeshBuffer(0), t, 4);
1252 setMeshBufferTextureCoords(mesh->getMeshBuffer(1), t, 4);
1257 // Do not pass by reference, see header.
1258 void GenericCAO::updateTextures(std::string mod)
1260 ITextureSource *tsrc = m_client->tsrc();
1262 bool use_trilinear_filter = g_settings->getBool("trilinear_filter");
1263 bool use_bilinear_filter = g_settings->getBool("bilinear_filter");
1264 bool use_anisotropic_filter = g_settings->getBool("anisotropic_filter");
1266 m_previous_texture_modifier = m_current_texture_modifier;
1267 m_current_texture_modifier = mod;
1268 m_glow = m_prop.glow;
1271 if (m_prop.visual == "sprite") {
1272 std::string texturestring = "unknown_node.png";
1273 if (!m_prop.textures.empty())
1274 texturestring = m_prop.textures[0];
1275 texturestring += mod;
1276 m_spritenode->getMaterial(0).MaterialType = m_material_type;
1277 m_spritenode->getMaterial(0).MaterialTypeParam = 0.5f;
1278 m_spritenode->setMaterialTexture(0,
1279 tsrc->getTextureForMesh(texturestring));
1281 // This allows setting per-material colors. However, until a real lighting
1282 // system is added, the code below will have no effect. Once MineTest
1283 // has directional lighting, it should work automatically.
1284 if (!m_prop.colors.empty()) {
1285 m_spritenode->getMaterial(0).AmbientColor = m_prop.colors[0];
1286 m_spritenode->getMaterial(0).DiffuseColor = m_prop.colors[0];
1287 m_spritenode->getMaterial(0).SpecularColor = m_prop.colors[0];
1290 m_spritenode->getMaterial(0).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1291 m_spritenode->getMaterial(0).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1292 m_spritenode->getMaterial(0).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1296 else if (m_animated_meshnode) {
1297 if (m_prop.visual == "mesh") {
1298 for (u32 i = 0; i < m_prop.textures.size() &&
1299 i < m_animated_meshnode->getMaterialCount(); ++i) {
1300 std::string texturestring = m_prop.textures[i];
1301 if (texturestring.empty())
1302 continue; // Empty texture string means don't modify that material
1303 texturestring += mod;
1304 video::ITexture* texture = tsrc->getTextureForMesh(texturestring);
1306 errorstream<<"GenericCAO::updateTextures(): Could not load texture "<<texturestring<<std::endl;
1310 // Set material flags and texture
1311 video::SMaterial& material = m_animated_meshnode->getMaterial(i);
1312 material.MaterialType = m_material_type;
1313 material.MaterialTypeParam = 0.5f;
1314 material.TextureLayer[0].Texture = texture;
1315 material.setFlag(video::EMF_LIGHTING, true);
1316 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1317 material.setFlag(video::EMF_BACK_FACE_CULLING, m_prop.backface_culling);
1319 // don't filter low-res textures, makes them look blurry
1320 // player models have a res of 64
1321 const core::dimension2d<u32> &size = texture->getOriginalSize();
1322 const u32 res = std::min(size.Height, size.Width);
1323 use_trilinear_filter &= res > 64;
1324 use_bilinear_filter &= res > 64;
1326 m_animated_meshnode->getMaterial(i)
1327 .setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1328 m_animated_meshnode->getMaterial(i)
1329 .setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1330 m_animated_meshnode->getMaterial(i)
1331 .setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1333 for (u32 i = 0; i < m_prop.colors.size() &&
1334 i < m_animated_meshnode->getMaterialCount(); ++i)
1336 // This allows setting per-material colors. However, until a real lighting
1337 // system is added, the code below will have no effect. Once MineTest
1338 // has directional lighting, it should work automatically.
1339 m_animated_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1340 m_animated_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1341 m_animated_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1346 else if (m_meshnode) {
1347 if(m_prop.visual == "cube")
1349 for (u32 i = 0; i < 6; ++i)
1351 std::string texturestring = "unknown_node.png";
1352 if(m_prop.textures.size() > i)
1353 texturestring = m_prop.textures[i];
1354 texturestring += mod;
1357 // Set material flags and texture
1358 video::SMaterial& material = m_meshnode->getMaterial(i);
1359 material.MaterialType = m_material_type;
1360 material.MaterialTypeParam = 0.5f;
1361 material.setFlag(video::EMF_LIGHTING, false);
1362 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1363 material.setTexture(0,
1364 tsrc->getTextureForMesh(texturestring));
1365 material.getTextureMatrix(0).makeIdentity();
1367 // This allows setting per-material colors. However, until a real lighting
1368 // system is added, the code below will have no effect. Once MineTest
1369 // has directional lighting, it should work automatically.
1370 if(m_prop.colors.size() > i)
1372 m_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1373 m_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1374 m_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1377 m_meshnode->getMaterial(i).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1378 m_meshnode->getMaterial(i).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1379 m_meshnode->getMaterial(i).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1381 } else if (m_prop.visual == "upright_sprite") {
1382 scene::IMesh *mesh = m_meshnode->getMesh();
1384 std::string tname = "unknown_object.png";
1385 if (!m_prop.textures.empty())
1386 tname = m_prop.textures[0];
1388 scene::IMeshBuffer *buf = mesh->getMeshBuffer(0);
1389 buf->getMaterial().setTexture(0,
1390 tsrc->getTextureForMesh(tname));
1392 // This allows setting per-material colors. However, until a real lighting
1393 // system is added, the code below will have no effect. Once MineTest
1394 // has directional lighting, it should work automatically.
1395 if(!m_prop.colors.empty()) {
1396 buf->getMaterial().AmbientColor = m_prop.colors[0];
1397 buf->getMaterial().DiffuseColor = m_prop.colors[0];
1398 buf->getMaterial().SpecularColor = m_prop.colors[0];
1401 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1402 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1403 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1406 std::string tname = "unknown_object.png";
1407 if (m_prop.textures.size() >= 2)
1408 tname = m_prop.textures[1];
1409 else if (!m_prop.textures.empty())
1410 tname = m_prop.textures[0];
1412 scene::IMeshBuffer *buf = mesh->getMeshBuffer(1);
1413 buf->getMaterial().setTexture(0,
1414 tsrc->getTextureForMesh(tname));
1416 // This allows setting per-material colors. However, until a real lighting
1417 // system is added, the code below will have no effect. Once MineTest
1418 // has directional lighting, it should work automatically.
1419 if (m_prop.colors.size() >= 2) {
1420 buf->getMaterial().AmbientColor = m_prop.colors[1];
1421 buf->getMaterial().DiffuseColor = m_prop.colors[1];
1422 buf->getMaterial().SpecularColor = m_prop.colors[1];
1423 } else if (!m_prop.colors.empty()) {
1424 buf->getMaterial().AmbientColor = m_prop.colors[0];
1425 buf->getMaterial().DiffuseColor = m_prop.colors[0];
1426 buf->getMaterial().SpecularColor = m_prop.colors[0];
1429 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1430 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1431 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1433 // Set mesh color (only if lighting is disabled)
1434 if (!m_prop.colors.empty() && m_glow < 0)
1435 setMeshColor(mesh, m_prop.colors[0]);
1438 // Prevent showing the player after changing texture
1439 if (m_is_local_player)
1440 updateMeshCulling();
1443 void GenericCAO::updateAnimation()
1445 if (!m_animated_meshnode)
1448 if (m_animated_meshnode->getStartFrame() != m_animation_range.X ||
1449 m_animated_meshnode->getEndFrame() != m_animation_range.Y)
1450 m_animated_meshnode->setFrameLoop(m_animation_range.X, m_animation_range.Y);
1451 if (m_animated_meshnode->getAnimationSpeed() != m_animation_speed)
1452 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1453 m_animated_meshnode->setTransitionTime(m_animation_blend);
1454 // Requires Irrlicht 1.8 or greater
1455 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR > 1
1456 if (m_animated_meshnode->getLoopMode() != m_animation_loop)
1457 m_animated_meshnode->setLoopMode(m_animation_loop);
1461 void GenericCAO::updateAnimationSpeed()
1463 if (!m_animated_meshnode)
1466 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1469 void GenericCAO::updateBonePosition()
1471 if (m_bone_position.empty() || !m_animated_meshnode)
1474 m_animated_meshnode->setJointMode(irr::scene::EJUOR_CONTROL); // To write positions to the mesh on render
1475 for (auto &it : m_bone_position) {
1476 std::string bone_name = it.first;
1477 irr::scene::IBoneSceneNode* bone = m_animated_meshnode->getJointNode(bone_name.c_str());
1479 bone->setPosition(it.second.X);
1480 bone->setRotation(it.second.Y);
1484 // search through bones to find mistakenly rotated bones due to bug in Irrlicht
1485 for (u32 i = 0; i < m_animated_meshnode->getJointCount(); ++i) {
1486 irr::scene::IBoneSceneNode *bone = m_animated_meshnode->getJointNode(i);
1490 // Workaround for Irrlicht bug
1491 // We check each bone to see if it has been rotated ~180deg from its expected position due to a bug in Irricht
1492 // when using EJUOR_CONTROL joint control. If the bug is detected we update the bone to the proper position
1493 // and update the bones transformation.
1494 v3f bone_rot = bone->getRelativeTransformation().getRotationDegrees();
1495 float offset_X = fabsf(bone_rot.X - bone->getRotation().X);
1496 float offset_Y = fabsf(bone_rot.Y - bone->getRotation().Y);
1497 float offset_Z = fabsf(bone_rot.Z - bone->getRotation().Z);
1498 if ((offset_X > 179.9f && offset_X < 180.1f)
1499 || (offset_Y > 179.9f && offset_Y < 180.1f)
1500 || (offset_Z > 179.9f && offset_Z < 180.1f)) {
1501 bone->setRotation(bone_rot);
1502 bone->updateAbsolutePosition();
1505 // The following is needed for set_bone_pos to propagate to
1506 // attached objects correctly.
1507 // Irrlicht ought to do this, but doesn't when using EJUOR_CONTROL.
1508 for (u32 i = 0; i < m_animated_meshnode->getJointCount(); ++i) {
1509 auto bone = m_animated_meshnode->getJointNode(i);
1510 // Look for the root bone.
1511 if (bone && bone->getParent() == m_animated_meshnode) {
1512 // Update entire skeleton.
1513 bone->updateAbsolutePositionOfAllChildren();
1519 void GenericCAO::updateAttachments()
1521 ClientActiveObject *parent = getParent();
1523 m_attached_to_local = parent && parent->isLocalPlayer();
1526 Following cases exist:
1527 m_attachment_parent_id == 0 && !parent
1528 This object is not attached
1529 m_attachment_parent_id != 0 && parent
1530 This object is attached
1531 m_attachment_parent_id != 0 && !parent
1532 This object will be attached as soon the parent is known
1533 m_attachment_parent_id == 0 && parent
1537 if (!parent) { // Detach or don't attach
1539 v3s16 camera_offset = m_env->getCameraOffset();
1540 v3f old_pos = getPosition();
1542 m_matrixnode->setParent(m_smgr->getRootSceneNode());
1543 getPosRotMatrix().setTranslation(old_pos - intToFloat(camera_offset, BS));
1544 m_matrixnode->updateAbsolutePosition();
1549 parent->updateAttachments();
1550 scene::ISceneNode *parent_node = parent->getSceneNode();
1551 scene::IAnimatedMeshSceneNode *parent_animated_mesh_node =
1552 parent->getAnimatedMeshSceneNode();
1553 if (parent_animated_mesh_node && !m_attachment_bone.empty()) {
1554 parent_node = parent_animated_mesh_node->getJointNode(m_attachment_bone.c_str());
1557 if (m_matrixnode && parent_node) {
1558 m_matrixnode->setParent(parent_node);
1559 parent_node->updateAbsolutePosition();
1560 getPosRotMatrix().setTranslation(m_attachment_position);
1561 //setPitchYawRoll(getPosRotMatrix(), m_attachment_rotation);
1562 // use Irrlicht eulers instead
1563 getPosRotMatrix().setRotationDegrees(m_attachment_rotation);
1564 m_matrixnode->updateAbsolutePosition();
1569 bool GenericCAO::visualExpiryRequired(const ObjectProperties &new_) const
1571 const ObjectProperties &old = m_prop;
1572 /* Visuals do not need to be expired for:
1573 * - nametag props: handled by updateNametag()
1574 * - textures: handled by updateTextures()
1575 * - sprite props: handled by updateTexturePos()
1576 * - glow: handled by updateLight()
1577 * - any other properties that do not change appearance
1580 bool uses_legacy_texture = new_.wield_item.empty() &&
1581 (new_.visual == "wielditem" || new_.visual == "item");
1582 // Ordered to compare primitive types before std::vectors
1583 return old.backface_culling != new_.backface_culling ||
1584 old.is_visible != new_.is_visible ||
1585 old.mesh != new_.mesh ||
1586 old.shaded != new_.shaded ||
1587 old.use_texture_alpha != new_.use_texture_alpha ||
1588 old.visual != new_.visual ||
1589 old.visual_size != new_.visual_size ||
1590 old.wield_item != new_.wield_item ||
1591 old.colors != new_.colors ||
1592 (uses_legacy_texture && old.textures != new_.textures);
1595 void GenericCAO::processMessage(const std::string &data)
1597 //infostream<<"GenericCAO: Got message"<<std::endl;
1598 std::istringstream is(data, std::ios::binary);
1600 u8 cmd = readU8(is);
1601 if (cmd == AO_CMD_SET_PROPERTIES) {
1602 ObjectProperties newprops;
1603 newprops.show_on_minimap = m_is_player; // default
1605 newprops.deSerialize(is);
1607 // Check what exactly changed
1608 bool expire_visuals = visualExpiryRequired(newprops);
1609 bool textures_changed = m_prop.textures != newprops.textures;
1612 m_prop = std::move(newprops);
1614 m_selection_box = m_prop.selectionbox;
1615 m_selection_box.MinEdge *= BS;
1616 m_selection_box.MaxEdge *= BS;
1618 m_tx_size.X = 1.0f / m_prop.spritediv.X;
1619 m_tx_size.Y = 1.0f / m_prop.spritediv.Y;
1621 if(!m_initial_tx_basepos_set){
1622 m_initial_tx_basepos_set = true;
1623 m_tx_basepos = m_prop.initial_sprite_basepos;
1625 if (m_is_local_player) {
1626 LocalPlayer *player = m_env->getLocalPlayer();
1627 player->makes_footstep_sound = m_prop.makes_footstep_sound;
1628 aabb3f collision_box = m_prop.collisionbox;
1629 collision_box.MinEdge *= BS;
1630 collision_box.MaxEdge *= BS;
1631 player->setCollisionbox(collision_box);
1632 player->setEyeHeight(m_prop.eye_height);
1633 player->setZoomFOV(m_prop.zoom_fov);
1636 if ((m_is_player && !m_is_local_player) && m_prop.nametag.empty())
1637 m_prop.nametag = m_name;
1638 if (m_is_local_player)
1639 m_prop.show_on_minimap = false;
1641 if (expire_visuals) {
1644 infostream << "GenericCAO: properties updated but expiring visuals"
1645 << " not necessary" << std::endl;
1646 if (textures_changed) {
1647 // don't update while punch texture modifier is active
1648 if (m_reset_textures_timer < 0)
1649 updateTextures(m_current_texture_modifier);
1654 } else if (cmd == AO_CMD_UPDATE_POSITION) {
1655 // Not sent by the server if this object is an attachment.
1656 // We might however get here if the server notices the object being detached before the client.
1657 m_position = readV3F32(is);
1658 m_velocity = readV3F32(is);
1659 m_acceleration = readV3F32(is);
1660 m_rotation = readV3F32(is);
1662 m_rotation = wrapDegrees_0_360_v3f(m_rotation);
1663 bool do_interpolate = readU8(is);
1664 bool is_end_position = readU8(is);
1665 float update_interval = readF32(is);
1667 // Place us a bit higher if we're physical, to not sink into
1668 // the ground due to sucky collision detection...
1670 m_position += v3f(0,0.002,0);
1672 if(getParent() != NULL) // Just in case
1677 if(!m_prop.physical)
1678 pos_translator.update(m_position, is_end_position, update_interval);
1680 pos_translator.init(m_position);
1682 rot_translator.update(m_rotation, false, update_interval);
1684 } else if (cmd == AO_CMD_SET_TEXTURE_MOD) {
1685 std::string mod = deSerializeString16(is);
1687 // immediately reset a engine issued texture modifier if a mod sends a different one
1688 if (m_reset_textures_timer > 0) {
1689 m_reset_textures_timer = -1;
1690 updateTextures(m_previous_texture_modifier);
1692 updateTextures(mod);
1693 } else if (cmd == AO_CMD_SET_SPRITE) {
1694 v2s16 p = readV2S16(is);
1695 int num_frames = readU16(is);
1696 float framelength = readF32(is);
1697 bool select_horiz_by_yawpitch = readU8(is);
1700 m_anim_num_frames = num_frames;
1701 m_anim_framelength = framelength;
1702 m_tx_select_horiz_by_yawpitch = select_horiz_by_yawpitch;
1705 } else if (cmd == AO_CMD_SET_PHYSICS_OVERRIDE) {
1706 float override_speed = readF32(is);
1707 float override_jump = readF32(is);
1708 float override_gravity = readF32(is);
1709 // these are sent inverted so we get true when the server sends nothing
1710 bool sneak = !readU8(is);
1711 bool sneak_glitch = !readU8(is);
1712 bool new_move = !readU8(is);
1715 if(m_is_local_player)
1717 LocalPlayer *player = m_env->getLocalPlayer();
1718 player->physics_override_speed = override_speed;
1719 player->physics_override_jump = override_jump;
1720 player->physics_override_gravity = override_gravity;
1721 player->physics_override_sneak = sneak;
1722 player->physics_override_sneak_glitch = sneak_glitch;
1723 player->physics_override_new_move = new_move;
1725 } else if (cmd == AO_CMD_SET_ANIMATION) {
1726 // TODO: change frames send as v2s32 value
1727 v2f range = readV2F32(is);
1728 if (!m_is_local_player) {
1729 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1730 m_animation_speed = readF32(is);
1731 m_animation_blend = readF32(is);
1732 // these are sent inverted so we get true when the server sends nothing
1733 m_animation_loop = !readU8(is);
1736 LocalPlayer *player = m_env->getLocalPlayer();
1737 if(player->last_animation == NO_ANIM)
1739 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1740 m_animation_speed = readF32(is);
1741 m_animation_blend = readF32(is);
1742 // these are sent inverted so we get true when the server sends nothing
1743 m_animation_loop = !readU8(is);
1745 // update animation only if local animations present
1746 // and received animation is unknown (except idle animation)
1747 bool is_known = false;
1748 for (int i = 1;i<4;i++)
1750 if(m_animation_range.Y == player->local_animations[i].Y)
1754 (player->local_animations[1].Y + player->local_animations[2].Y < 1))
1759 } else if (cmd == AO_CMD_SET_ANIMATION_SPEED) {
1760 m_animation_speed = readF32(is);
1761 updateAnimationSpeed();
1762 } else if (cmd == AO_CMD_SET_BONE_POSITION) {
1763 std::string bone = deSerializeString16(is);
1764 v3f position = readV3F32(is);
1765 v3f rotation = readV3F32(is);
1766 m_bone_position[bone] = core::vector2d<v3f>(position, rotation);
1768 // updateBonePosition(); now called every step
1769 } else if (cmd == AO_CMD_ATTACH_TO) {
1770 u16 parent_id = readS16(is);
1771 std::string bone = deSerializeString16(is);
1772 v3f position = readV3F32(is);
1773 v3f rotation = readV3F32(is);
1774 m_force_visible = readU8(is); // Returns false for EOF
1776 setAttachment(parent_id, bone, position, rotation);
1778 // Forcibly show attachments if required by set_attach
1779 if (m_force_visible)
1780 m_is_visible = true;
1781 // localplayer itself can't be attached to localplayer
1782 else if (!m_is_local_player) {
1783 // Objects attached to the local player should be hidden in first
1784 // person provided the forced boolean isn't set.
1785 m_is_visible = !m_attached_to_local ||
1786 m_client->getCamera()->getCameraMode() != CAMERA_MODE_FIRST;
1787 m_force_visible = false;
1789 // Local players need to have this set,
1790 // otherwise first person attachments fail.
1791 m_is_visible = true;
1793 } else if (cmd == AO_CMD_PUNCHED) {
1794 u16 result_hp = readU16(is);
1796 // Use this instead of the send damage to not interfere with prediction
1797 s32 damage = (s32)m_hp - (s32)result_hp;
1801 if (m_is_local_player)
1802 m_env->getLocalPlayer()->hp = m_hp;
1808 // TODO: Execute defined fast response
1809 // As there is no definition, make a smoke puff
1810 ClientSimpleObject *simple = createSmokePuff(
1811 m_smgr, m_env, m_position,
1812 v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
1813 m_env->addSimpleObject(simple);
1814 } else if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
1815 m_reset_textures_timer = 0.05;
1817 m_reset_textures_timer += 0.05 * damage;
1818 updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
1823 // Same as 'Server::DiePlayer'
1824 clearParentAttachment();
1825 // Same as 'ObjectRef::l_remove'
1827 clearChildAttachments();
1829 } else if (cmd == AO_CMD_UPDATE_ARMOR_GROUPS) {
1830 m_armor_groups.clear();
1831 int armor_groups_size = readU16(is);
1832 for(int i=0; i<armor_groups_size; i++)
1834 std::string name = deSerializeString16(is);
1835 int rating = readS16(is);
1836 m_armor_groups[name] = rating;
1838 } else if (cmd == AO_CMD_SPAWN_INFANT) {
1839 u16 child_id = readU16(is);
1840 u8 type = readU8(is); // maybe this will be useful later
1843 addAttachmentChild(child_id);
1844 } else if (cmd == AO_CMD_OBSOLETE1) {
1845 // Don't do anything and also don't log a warning
1847 warningstream << FUNCTION_NAME
1848 << ": unknown command or outdated client \""
1849 << +cmd << "\"" << std::endl;
1853 /* \pre punchitem != NULL
1855 bool GenericCAO::directReportPunch(v3f dir, const ItemStack *punchitem,
1856 float time_from_last_punch)
1858 assert(punchitem); // pre-condition
1859 const ToolCapabilities *toolcap =
1860 &punchitem->getToolCapabilities(m_client->idef());
1861 PunchDamageResult result = getPunchDamage(
1865 time_from_last_punch);
1867 if(result.did_punch && result.damage != 0)
1869 if(result.damage < m_hp)
1871 m_hp -= result.damage;
1874 // TODO: Execute defined fast response
1875 // As there is no definition, make a smoke puff
1876 ClientSimpleObject *simple = createSmokePuff(
1877 m_smgr, m_env, m_position,
1878 v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
1879 m_env->addSimpleObject(simple);
1881 if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
1882 m_reset_textures_timer = 0.05;
1883 if (result.damage >= 2)
1884 m_reset_textures_timer += 0.05 * result.damage;
1885 updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
1892 std::string GenericCAO::debugInfoText()
1894 std::ostringstream os(std::ios::binary);
1895 os<<"GenericCAO hp="<<m_hp<<"\n";
1897 for(ItemGroupList::const_iterator i = m_armor_groups.begin();
1898 i != m_armor_groups.end(); ++i)
1900 os<<i->first<<"="<<i->second<<", ";
1906 void GenericCAO::updateMeshCulling()
1908 if (!m_is_local_player)
1911 // Grab the active player scene node so we know there's
1912 // at least a mesh to occlude from the camera.
1913 irr::scene::ISceneNode *node = getSceneNode();
1917 if (m_client->getCamera()->getCameraMode() == CAMERA_MODE_FIRST) {
1918 // Hide the mesh by culling both front and
1919 // back faces. Serious hackyness but it works for our
1920 // purposes. This also preserves the skeletal armature.
1921 node->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
1923 node->setMaterialFlag(video::EMF_FRONT_FACE_CULLING,
1926 // Restore mesh visibility.
1927 node->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
1928 m_prop.backface_culling);
1929 node->setMaterialFlag(video::EMF_FRONT_FACE_CULLING,
1935 GenericCAO proto_GenericCAO(NULL, NULL);