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 <ICameraSceneNode.h>
21 #include <ITextSceneNode.h>
22 #include <IBillboardSceneNode.h>
23 #include <IMeshManipulator.h>
24 #include <IAnimatedMeshSceneNode.h>
25 #include "content_cao.h"
26 #include "util/numeric.h" // For IntervalLimiter
27 #include "util/serialize.h"
28 #include "util/basic_macros.h"
29 #include "client/tile.h"
30 #include "environment.h"
31 #include "collision.h"
33 #include "serialization.h" // For decompressZlib
34 #include "clientobject.h"
38 #include "content_cso.h"
41 #include "localplayer.h"
43 #include "camera.h" // CameraModes
45 #include "wieldmesh.h"
47 #include "client/renderingengine.h"
50 struct ToolCapabilities;
52 std::unordered_map<u16, ClientActiveObject::Factory> ClientActiveObject::m_types;
54 void SmoothTranslator::init(v3f vect)
61 anim_time_counter = 0;
65 void SmoothTranslator::update(v3f vect_new, bool is_end_position, float update_interval)
67 aim_is_end = is_end_position;
70 if(update_interval > 0)
72 anim_time = update_interval;
74 if(anim_time < 0.001 || anim_time > 1.0)
75 anim_time = anim_time_counter;
77 anim_time = anim_time * 0.9 + anim_time_counter * 0.1;
79 anim_time_counter = 0;
83 void SmoothTranslator::translate(f32 dtime)
85 anim_time_counter = anim_time_counter + dtime;
86 anim_counter = anim_counter + dtime;
87 v3f vect_move = vect_aim - vect_old;
90 moveratio = anim_time_counter / anim_time;
91 // Move a bit less than should, to avoid oscillation
92 moveratio = moveratio * 0.8;
96 if(moveratio > move_end)
98 vect_show = vect_old + vect_move * moveratio;
105 static void setBillboardTextureMatrix(scene::IBillboardSceneNode *bill,
106 float txs, float tys, int col, int row)
108 video::SMaterial& material = bill->getMaterial(0);
109 core::matrix4& matrix = material.getTextureMatrix(0);
110 matrix.setTextureTranslate(txs*col, tys*row);
111 matrix.setTextureScale(txs, tys);
118 class TestCAO : public ClientActiveObject
121 TestCAO(Client *client, ClientEnvironment *env);
122 virtual ~TestCAO() = default;
124 ActiveObjectType getType() const
126 return ACTIVEOBJECT_TYPE_TEST;
129 static ClientActiveObject* create(Client *client, ClientEnvironment *env);
131 void addToScene(ITextureSource *tsrc);
132 void removeFromScene(bool permanent);
133 void updateLight(u8 light_at_pos);
134 v3s16 getLightPosition();
135 void updateNodePos();
137 void step(float dtime, ClientEnvironment *env);
139 void processMessage(const std::string &data);
141 bool getCollisionBox(aabb3f *toset) const { return false; }
143 scene::IMeshSceneNode *m_node;
148 TestCAO proto_TestCAO(NULL, NULL);
150 TestCAO::TestCAO(Client *client, ClientEnvironment *env):
151 ClientActiveObject(0, client, env),
153 m_position(v3f(0,10*BS,0))
155 ClientActiveObject::registerType(getType(), create);
158 ClientActiveObject* TestCAO::create(Client *client, ClientEnvironment *env)
160 return new TestCAO(client, env);
163 void TestCAO::addToScene(ITextureSource *tsrc)
168 //video::IVideoDriver* driver = smgr->getVideoDriver();
170 scene::SMesh *mesh = new scene::SMesh();
171 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
172 video::SColor c(255,255,255,255);
173 video::S3DVertex vertices[4] =
175 video::S3DVertex(-BS/2,-BS/4,0, 0,0,0, c, 0,1),
176 video::S3DVertex(BS/2,-BS/4,0, 0,0,0, c, 1,1),
177 video::S3DVertex(BS/2,BS/4,0, 0,0,0, c, 1,0),
178 video::S3DVertex(-BS/2,BS/4,0, 0,0,0, c, 0,0),
180 u16 indices[] = {0,1,2,2,3,0};
181 buf->append(vertices, 4, indices, 6);
183 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
184 buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
185 buf->getMaterial().setTexture(0, tsrc->getTextureForMesh("rat.png"));
186 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
187 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
188 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
190 mesh->addMeshBuffer(buf);
192 m_node = RenderingEngine::get_scene_manager()->addMeshSceneNode(mesh, NULL);
197 void TestCAO::removeFromScene(bool permanent)
206 void TestCAO::updateLight(u8 light_at_pos)
210 v3s16 TestCAO::getLightPosition()
212 return floatToInt(m_position, BS);
215 void TestCAO::updateNodePos()
220 m_node->setPosition(m_position);
221 //m_node->setRotation(v3f(0, 45, 0));
224 void TestCAO::step(float dtime, ClientEnvironment *env)
228 v3f rot = m_node->getRotation();
229 //infostream<<"dtime="<<dtime<<", rot.Y="<<rot.Y<<std::endl;
230 rot.Y += dtime * 180;
231 m_node->setRotation(rot);
235 void TestCAO::processMessage(const std::string &data)
237 infostream<<"TestCAO: Got data: "<<data<<std::endl;
238 std::istringstream is(data, std::ios::binary);
256 #include "genericobject.h"
258 GenericCAO::GenericCAO(Client *client, ClientEnvironment *env):
259 ClientActiveObject(0, client, env)
261 if (client == NULL) {
262 ClientActiveObject::registerType(getType(), create);
268 bool GenericCAO::getCollisionBox(aabb3f *toset) const
272 //update collision box
273 toset->MinEdge = m_prop.collisionbox.MinEdge * BS;
274 toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS;
276 toset->MinEdge += m_position;
277 toset->MaxEdge += m_position;
285 bool GenericCAO::collideWithObjects() const
287 return m_prop.collideWithObjects;
290 void GenericCAO::initialize(const std::string &data)
292 infostream<<"GenericCAO: Got init data"<<std::endl;
293 processInitData(data);
296 // Check if it's the current player
297 LocalPlayer *player = m_env->getLocalPlayer();
298 if (player && strcmp(player->getName(), m_name.c_str()) == 0) {
299 m_is_local_player = true;
300 m_is_visible = false;
301 player->setCAO(this);
303 if (m_client->getProtoVersion() < 33)
304 m_env->addPlayerName(m_name);
308 void GenericCAO::processInitData(const std::string &data)
310 std::istringstream is(data, std::ios::binary);
311 int num_messages = 0;
313 u8 version = readU8(is);
315 if (version == 1) { // In PROTOCOL_VERSION 14
316 m_name = deSerializeString(is);
317 m_is_player = readU8(is);
319 m_position = readV3F1000(is);
320 m_yaw = readF1000(is);
322 num_messages = readU8(is);
324 errorstream<<"GenericCAO: Unsupported init data version"
329 for (int i = 0; i < num_messages; i++) {
330 std::string message = deSerializeLongString(is);
331 processMessage(message);
334 pos_translator.init(m_position);
338 GenericCAO::~GenericCAO()
340 if (m_is_player && m_client->getProtoVersion() < 33) {
341 m_env->removePlayerName(m_name);
343 removeFromScene(true);
346 bool GenericCAO::getSelectionBox(aabb3f *toset) const
348 if (!m_prop.is_visible || !m_is_visible || m_is_local_player
349 || getParent() != NULL){
352 *toset = m_selection_box;
356 v3f GenericCAO::getPosition()
358 if (getParent() != NULL) {
359 scene::ISceneNode *node = getSceneNode();
361 return node->getAbsolutePosition();
365 return pos_translator.vect_show;
368 scene::ISceneNode* GenericCAO::getSceneNode()
374 if (m_animated_meshnode) {
375 return m_animated_meshnode;
378 if (m_wield_meshnode) {
379 return m_wield_meshnode;
388 scene::IAnimatedMeshSceneNode* GenericCAO::getAnimatedMeshSceneNode()
390 return m_animated_meshnode;
393 void GenericCAO::setChildrenVisible(bool toset)
395 for (u16 cao_id : m_children) {
396 GenericCAO *obj = m_env->getGenericCAO(cao_id);
398 obj->setVisible(toset);
403 void GenericCAO::setAttachments()
408 ClientActiveObject* GenericCAO::getParent() const
410 ClientActiveObject *obj = NULL;
412 u16 attached_id = m_env->attachement_parent_ids[getId()];
414 if ((attached_id != 0) &&
415 (attached_id != getId())) {
416 obj = m_env->getActiveObject(attached_id);
421 void GenericCAO::removeFromScene(bool permanent)
423 // Should be true when removing the object permanently and false when refreshing (eg: updating visuals)
424 if((m_env != NULL) && (permanent))
426 for (u16 ci : m_children) {
427 if (m_env->attachement_parent_ids[ci] == getId()) {
428 m_env->attachement_parent_ids[ci] = 0;
432 m_env->attachement_parent_ids[getId()] = 0;
434 LocalPlayer* player = m_env->getLocalPlayer();
435 if (this == player->parent) {
436 player->parent = NULL;
437 player->isAttached = false;
442 m_meshnode->remove();
445 } else if (m_animated_meshnode) {
446 m_animated_meshnode->remove();
447 m_animated_meshnode->drop();
448 m_animated_meshnode = NULL;
449 } else if (m_wield_meshnode) {
450 m_wield_meshnode->remove();
451 m_wield_meshnode->drop();
452 m_wield_meshnode = NULL;
453 } else if (m_spritenode) {
454 m_spritenode->remove();
455 m_spritenode->drop();
460 m_client->getCamera()->removeNametag(m_nametag);
465 void GenericCAO::addToScene(ITextureSource *tsrc)
467 m_smgr = RenderingEngine::get_scene_manager();
469 if (getSceneNode() != NULL) {
473 m_visuals_expired = false;
475 if (!m_prop.is_visible) {
479 if (m_prop.visual == "sprite") {
480 infostream<<"GenericCAO::addToScene(): single_sprite"<<std::endl;
481 m_spritenode = RenderingEngine::get_scene_manager()->addBillboardSceneNode(
482 NULL, v2f(1, 1), v3f(0,0,0), -1);
483 m_spritenode->grab();
484 m_spritenode->setMaterialTexture(0,
485 tsrc->getTextureForMesh("unknown_node.png"));
486 m_spritenode->setMaterialFlag(video::EMF_LIGHTING, false);
487 m_spritenode->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
488 m_spritenode->setMaterialType(video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF);
489 m_spritenode->setMaterialFlag(video::EMF_FOG_ENABLE, true);
490 u8 li = m_last_light;
491 m_spritenode->setColor(video::SColor(255,li,li,li));
492 m_spritenode->setSize(m_prop.visual_size*BS);
494 const float txs = 1.0 / 1;
495 const float tys = 1.0 / 1;
496 setBillboardTextureMatrix(m_spritenode,
499 } else if (m_prop.visual == "upright_sprite") {
500 scene::SMesh *mesh = new scene::SMesh();
501 double dx = BS * m_prop.visual_size.X / 2;
502 double dy = BS * m_prop.visual_size.Y / 2;
503 u8 li = m_last_light;
504 video::SColor c(255, li, li, li);
507 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
508 video::S3DVertex vertices[4] = {
509 video::S3DVertex(-dx, -dy, 0, 0,0,0, c, 1,1),
510 video::S3DVertex( dx, -dy, 0, 0,0,0, c, 0,1),
511 video::S3DVertex( dx, dy, 0, 0,0,0, c, 0,0),
512 video::S3DVertex(-dx, dy, 0, 0,0,0, c, 1,0),
514 u16 indices[] = {0,1,2,2,3,0};
515 buf->append(vertices, 4, indices, 6);
517 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
518 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
519 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
520 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
522 mesh->addMeshBuffer(buf);
526 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
527 video::S3DVertex vertices[4] = {
528 video::S3DVertex( dx,-dy, 0, 0,0,0, c, 1,1),
529 video::S3DVertex(-dx,-dy, 0, 0,0,0, c, 0,1),
530 video::S3DVertex(-dx, dy, 0, 0,0,0, c, 0,0),
531 video::S3DVertex( dx, dy, 0, 0,0,0, c, 1,0),
533 u16 indices[] = {0,1,2,2,3,0};
534 buf->append(vertices, 4, indices, 6);
536 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
537 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
538 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
539 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
541 mesh->addMeshBuffer(buf);
544 m_meshnode = RenderingEngine::get_scene_manager()->addMeshSceneNode(mesh, NULL);
547 // Set it to use the materials of the meshbuffers directly.
548 // This is needed for changing the texture in the future
549 m_meshnode->setReadOnlyMaterials(true);
551 else if(m_prop.visual == "cube") {
552 infostream<<"GenericCAO::addToScene(): cube"<<std::endl;
553 scene::IMesh *mesh = createCubeMesh(v3f(BS,BS,BS));
554 m_meshnode = RenderingEngine::get_scene_manager()->addMeshSceneNode(mesh, NULL);
558 m_meshnode->setScale(v3f(m_prop.visual_size.X,
559 m_prop.visual_size.Y,
560 m_prop.visual_size.X));
561 u8 li = m_last_light;
562 setMeshColor(m_meshnode->getMesh(), video::SColor(255,li,li,li));
564 m_meshnode->setMaterialFlag(video::EMF_LIGHTING, false);
565 m_meshnode->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
566 m_meshnode->setMaterialType(video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF);
567 m_meshnode->setMaterialFlag(video::EMF_FOG_ENABLE, true);
569 else if(m_prop.visual == "mesh") {
570 infostream<<"GenericCAO::addToScene(): mesh"<<std::endl;
571 scene::IAnimatedMesh *mesh = m_client->getMesh(m_prop.mesh);
574 m_animated_meshnode = RenderingEngine::get_scene_manager()->
575 addAnimatedMeshSceneNode(mesh, NULL);
576 m_animated_meshnode->grab();
577 mesh->drop(); // The scene node took hold of it
578 m_animated_meshnode->animateJoints(); // Needed for some animations
579 m_animated_meshnode->setScale(v3f(m_prop.visual_size.X,
580 m_prop.visual_size.Y,
581 m_prop.visual_size.X));
582 u8 li = m_last_light;
583 setMeshColor(m_animated_meshnode->getMesh(), video::SColor(255,li,li,li));
585 bool backface_culling = m_prop.backface_culling;
587 backface_culling = false;
589 m_animated_meshnode->setMaterialFlag(video::EMF_LIGHTING, false);
590 m_animated_meshnode->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
591 m_animated_meshnode->setMaterialType(video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF);
592 m_animated_meshnode->setMaterialFlag(video::EMF_FOG_ENABLE, true);
593 m_animated_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING, backface_culling);
596 errorstream<<"GenericCAO::addToScene(): Could not load mesh "<<m_prop.mesh<<std::endl;
597 } else if (m_prop.visual == "wielditem") {
599 infostream << "GenericCAO::addToScene(): wielditem" << std::endl;
600 if (m_prop.wield_item.empty()) {
601 // Old format, only textures are specified.
602 infostream << "textures: " << m_prop.textures.size() << std::endl;
603 if (!m_prop.textures.empty()) {
604 infostream << "textures[0]: " << m_prop.textures[0]
606 IItemDefManager *idef = m_client->idef();
607 item = ItemStack(m_prop.textures[0], 1, 0, idef);
610 infostream << "serialized form: " << m_prop.wield_item << std::endl;
611 item.deSerialize(m_prop.wield_item, m_client->idef());
613 m_wield_meshnode = new WieldMeshSceneNode(
614 RenderingEngine::get_scene_manager(), -1);
615 m_wield_meshnode->setItem(item, m_client);
617 m_wield_meshnode->setScale(
618 v3f(m_prop.visual_size.X / 2, m_prop.visual_size.Y / 2,
619 m_prop.visual_size.X / 2));
620 u8 li = m_last_light;
621 m_wield_meshnode->setColor(video::SColor(255, li, li, li));
623 infostream<<"GenericCAO::addToScene(): \""<<m_prop.visual
624 <<"\" not supported"<<std::endl;
627 /* don't update while punch texture modifier is active */
628 if (m_reset_textures_timer < 0)
629 updateTextures(m_current_texture_modifier);
631 scene::ISceneNode *node = getSceneNode();
632 if (node && !m_prop.nametag.empty() && !m_is_local_player) {
635 pos.Y = m_prop.collisionbox.MaxEdge.Y + 0.3f;
636 m_nametag = m_client->getCamera()->addNametag(node,
637 m_prop.nametag, m_prop.nametag_color,
643 updateBonePosition();
647 void GenericCAO::updateLight(u8 light_at_pos)
649 // Don't update light of attached one
650 if (getParent() != NULL) {
654 updateLightNoCheck(light_at_pos);
656 // Update light of all children
657 for (u16 i : m_children) {
658 ClientActiveObject *obj = m_env->getActiveObject(i);
660 obj->updateLightNoCheck(light_at_pos);
665 void GenericCAO::updateLightNoCheck(u8 light_at_pos)
667 u8 li = decode_light(light_at_pos);
668 if (li != m_last_light) {
670 video::SColor color(255,li,li,li);
672 setMeshColor(m_meshnode->getMesh(), color);
673 } else if (m_animated_meshnode) {
674 setMeshColor(m_animated_meshnode->getMesh(), color);
675 } else if (m_wield_meshnode) {
676 m_wield_meshnode->setColor(color);
677 } else if (m_spritenode) {
678 m_spritenode->setColor(color);
683 v3s16 GenericCAO::getLightPosition()
686 return floatToInt(m_position + v3f(0, 0.5 * BS, 0), BS);
688 return floatToInt(m_position, BS);
691 void GenericCAO::updateNodePos()
693 if (getParent() != NULL)
696 scene::ISceneNode *node = getSceneNode();
699 v3s16 camera_offset = m_env->getCameraOffset();
700 node->setPosition(pos_translator.vect_show - intToFloat(camera_offset, BS));
701 if (node != m_spritenode) { // rotate if not a sprite
702 v3f rot = node->getRotation();
704 node->setRotation(rot);
709 void GenericCAO::step(float dtime, ClientEnvironment *env)
711 // Handel model of local player instantly to prevent lags
712 if (m_is_local_player) {
713 LocalPlayer *player = m_env->getLocalPlayer();
715 int old_anim = player->last_animation;
716 float old_anim_speed = player->last_animation_speed;
717 m_position = player->getPosition();
718 m_velocity = v3f(0,0,0);
719 m_acceleration = v3f(0,0,0);
720 pos_translator.vect_show = m_position;
721 m_yaw = player->getYaw();
722 const PlayerControl &controls = player->getPlayerControl();
724 bool walking = false;
725 if (controls.up || controls.down || controls.left || controls.right ||
726 controls.forw_move_joystick_axis != 0.f ||
727 controls.sidew_move_joystick_axis != 0.f)
730 f32 new_speed = player->local_animation_speed;
731 v2s32 new_anim = v2s32(0,0);
732 bool allow_update = false;
734 // increase speed if using fast or flying fast
735 if((g_settings->getBool("fast_move") &&
736 m_client->checkLocalPrivilege("fast")) &&
738 (!player->touching_ground &&
739 g_settings->getBool("free_move") &&
740 m_client->checkLocalPrivilege("fly"))))
742 // slowdown speed if sneeking
743 if (controls.sneak && walking)
746 if (walking && (controls.LMB || controls.RMB)) {
747 new_anim = player->local_animations[3];
748 player->last_animation = WD_ANIM;
750 new_anim = player->local_animations[1];
751 player->last_animation = WALK_ANIM;
752 } else if(controls.LMB || controls.RMB) {
753 new_anim = player->local_animations[2];
754 player->last_animation = DIG_ANIM;
757 // Apply animations if input detected and not attached
758 // or set idle animation
759 if ((new_anim.X + new_anim.Y) > 0 && !player->isAttached) {
761 m_animation_range = new_anim;
762 m_animation_speed = new_speed;
763 player->last_animation_speed = m_animation_speed;
765 player->last_animation = NO_ANIM;
767 if (old_anim != NO_ANIM) {
768 m_animation_range = player->local_animations[0];
773 // Update local player animations
774 if ((player->last_animation != old_anim ||
775 m_animation_speed != old_anim_speed) &&
776 player->last_animation != NO_ANIM && allow_update)
782 if (m_visuals_expired && m_smgr) {
783 m_visuals_expired = false;
785 // Attachments, part 1: All attached objects must be unparented first,
786 // or Irrlicht causes a segmentation fault
787 for (auto ci = m_children.begin(); ci != m_children.end();) {
788 if (m_env->attachement_parent_ids[*ci] != getId()) {
789 ci = m_children.erase(ci);
792 ClientActiveObject *obj = m_env->getActiveObject(*ci);
794 scene::ISceneNode *child_node = obj->getSceneNode();
796 child_node->setParent(m_smgr->getRootSceneNode());
801 removeFromScene(false);
802 addToScene(m_client->tsrc());
804 // Attachments, part 2: Now that the parent has been refreshed, put its attachments back
805 for (u16 cao_id : m_children) {
806 // Get the object of the child
807 ClientActiveObject *obj = m_env->getActiveObject(cao_id);
809 obj->setAttachments();
813 // Make sure m_is_visible is always applied
814 scene::ISceneNode *node = getSceneNode();
816 node->setVisible(m_is_visible);
818 if(getParent() != NULL) // Attachments should be glued to their parent by Irrlicht
820 // Set these for later
821 m_position = getPosition();
822 m_velocity = v3f(0,0,0);
823 m_acceleration = v3f(0,0,0);
824 pos_translator.vect_show = m_position;
826 if(m_is_local_player) // Update local player attachment position
828 LocalPlayer *player = m_env->getLocalPlayer();
829 player->overridePosition = getParent()->getPosition();
830 m_env->getLocalPlayer()->parent = getParent();
833 v3f lastpos = pos_translator.vect_show;
837 aabb3f box = m_prop.collisionbox;
840 collisionMoveResult moveresult;
841 f32 pos_max_d = BS*0.125; // Distance per iteration
842 v3f p_pos = m_position;
843 v3f p_velocity = m_velocity;
844 moveresult = collisionMoveSimple(env,env->getGameDef(),
845 pos_max_d, box, m_prop.stepheight, dtime,
846 &p_pos, &p_velocity, m_acceleration,
847 this, m_prop.collideWithObjects);
850 m_velocity = p_velocity;
852 bool is_end_position = moveresult.collides;
853 pos_translator.update(m_position, is_end_position, dtime);
854 pos_translator.translate(dtime);
857 m_position += dtime * m_velocity + 0.5 * dtime * dtime * m_acceleration;
858 m_velocity += dtime * m_acceleration;
859 pos_translator.update(m_position, pos_translator.aim_is_end,
860 pos_translator.anim_time);
861 pos_translator.translate(dtime);
865 float moved = lastpos.getDistanceFrom(pos_translator.vect_show);
866 m_step_distance_counter += moved;
867 if(m_step_distance_counter > 1.5*BS)
869 m_step_distance_counter = 0;
870 if(!m_is_local_player && m_prop.makes_footstep_sound)
872 INodeDefManager *ndef = m_client->ndef();
873 v3s16 p = floatToInt(getPosition() + v3f(0,
874 (m_prop.collisionbox.MinEdge.Y-0.5)*BS, 0), BS);
875 MapNode n = m_env->getMap().getNodeNoEx(p);
876 SimpleSoundSpec spec = ndef->get(n).sound_footstep;
877 m_client->sound()->playSoundAt(spec, false, getPosition());
882 m_anim_timer += dtime;
883 if(m_anim_timer >= m_anim_framelength)
885 m_anim_timer -= m_anim_framelength;
887 if(m_anim_frame >= m_anim_num_frames)
893 if(m_reset_textures_timer >= 0)
895 m_reset_textures_timer -= dtime;
896 if(m_reset_textures_timer <= 0) {
897 m_reset_textures_timer = -1;
898 updateTextures(m_previous_texture_modifier);
901 if(!getParent() && fabs(m_prop.automatic_rotate) > 0.001)
903 m_yaw += dtime * m_prop.automatic_rotate * 180 / M_PI;
907 if (!getParent() && m_prop.automatic_face_movement_dir &&
908 (fabs(m_velocity.Z) > 0.001 || fabs(m_velocity.X) > 0.001))
910 float optimal_yaw = atan2(m_velocity.Z,m_velocity.X) * 180 / M_PI
911 + m_prop.automatic_face_movement_dir_offset;
912 float max_rotation_delta =
913 dtime * m_prop.automatic_face_movement_max_rotation_per_sec;
915 if ((m_prop.automatic_face_movement_max_rotation_per_sec > 0) &&
916 (fabs(m_yaw - optimal_yaw) > max_rotation_delta)) {
918 m_yaw = optimal_yaw < m_yaw ? m_yaw - max_rotation_delta : m_yaw + max_rotation_delta;
926 void GenericCAO::updateTexturePos()
930 scene::ICameraSceneNode* camera =
931 m_spritenode->getSceneManager()->getActiveCamera();
934 v3f cam_to_entity = m_spritenode->getAbsolutePosition()
935 - camera->getAbsolutePosition();
936 cam_to_entity.normalize();
938 int row = m_tx_basepos.Y;
939 int col = m_tx_basepos.X;
941 if(m_tx_select_horiz_by_yawpitch)
943 if(cam_to_entity.Y > 0.75)
945 else if(cam_to_entity.Y < -0.75)
949 atan2(cam_to_entity.Z, cam_to_entity.X) / M_PI * 180.;
950 float dir = mob_dir - m_yaw;
951 dir = wrapDegrees_180(dir);
952 //infostream<<"id="<<m_id<<" dir="<<dir<<std::endl;
953 if(fabs(wrapDegrees_180(dir - 0)) <= 45.1)
955 else if(fabs(wrapDegrees_180(dir - 90)) <= 45.1)
957 else if(fabs(wrapDegrees_180(dir - 180)) <= 45.1)
959 else if(fabs(wrapDegrees_180(dir + 90)) <= 45.1)
966 // Animation goes downwards
969 float txs = m_tx_size.X;
970 float tys = m_tx_size.Y;
971 setBillboardTextureMatrix(m_spritenode,
976 void GenericCAO::updateTextures(std::string mod)
978 ITextureSource *tsrc = m_client->tsrc();
980 bool use_trilinear_filter = g_settings->getBool("trilinear_filter");
981 bool use_bilinear_filter = g_settings->getBool("bilinear_filter");
982 bool use_anisotropic_filter = g_settings->getBool("anisotropic_filter");
984 m_previous_texture_modifier = m_current_texture_modifier;
985 m_current_texture_modifier = mod;
988 if (m_prop.visual == "sprite") {
989 std::string texturestring = "unknown_node.png";
990 if (!m_prop.textures.empty())
991 texturestring = m_prop.textures[0];
992 texturestring += mod;
993 m_spritenode->setMaterialTexture(0,
994 tsrc->getTextureForMesh(texturestring));
996 // This allows setting per-material colors. However, until a real lighting
997 // system is added, the code below will have no effect. Once MineTest
998 // has directional lighting, it should work automatically.
999 if (!m_prop.colors.empty()) {
1000 m_spritenode->getMaterial(0).AmbientColor = m_prop.colors[0];
1001 m_spritenode->getMaterial(0).DiffuseColor = m_prop.colors[0];
1002 m_spritenode->getMaterial(0).SpecularColor = m_prop.colors[0];
1005 m_spritenode->getMaterial(0).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1006 m_spritenode->getMaterial(0).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1007 m_spritenode->getMaterial(0).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1011 if (m_animated_meshnode) {
1012 if (m_prop.visual == "mesh") {
1013 for (u32 i = 0; i < m_prop.textures.size() &&
1014 i < m_animated_meshnode->getMaterialCount(); ++i) {
1015 std::string texturestring = m_prop.textures[i];
1016 if (texturestring.empty())
1017 continue; // Empty texture string means don't modify that material
1018 texturestring += mod;
1019 video::ITexture* texture = tsrc->getTextureForMesh(texturestring);
1021 errorstream<<"GenericCAO::updateTextures(): Could not load texture "<<texturestring<<std::endl;
1025 // Set material flags and texture
1026 video::SMaterial& material = m_animated_meshnode->getMaterial(i);
1027 material.TextureLayer[0].Texture = texture;
1028 material.setFlag(video::EMF_LIGHTING, false);
1029 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1031 m_animated_meshnode->getMaterial(i)
1032 .setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1033 m_animated_meshnode->getMaterial(i)
1034 .setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1035 m_animated_meshnode->getMaterial(i)
1036 .setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1038 for (u32 i = 0; i < m_prop.colors.size() &&
1039 i < m_animated_meshnode->getMaterialCount(); ++i)
1041 // This allows setting per-material colors. However, until a real lighting
1042 // system is added, the code below will have no effect. Once MineTest
1043 // has directional lighting, it should work automatically.
1044 m_animated_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1045 m_animated_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1046 m_animated_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1052 if(m_prop.visual == "cube")
1054 for (u32 i = 0; i < 6; ++i)
1056 std::string texturestring = "unknown_node.png";
1057 if(m_prop.textures.size() > i)
1058 texturestring = m_prop.textures[i];
1059 texturestring += mod;
1062 // Set material flags and texture
1063 video::SMaterial& material = m_meshnode->getMaterial(i);
1064 material.setFlag(video::EMF_LIGHTING, false);
1065 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1066 material.setTexture(0,
1067 tsrc->getTextureForMesh(texturestring));
1068 material.getTextureMatrix(0).makeIdentity();
1070 // This allows setting per-material colors. However, until a real lighting
1071 // system is added, the code below will have no effect. Once MineTest
1072 // has directional lighting, it should work automatically.
1073 if(m_prop.colors.size() > i)
1075 m_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1076 m_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1077 m_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1080 m_meshnode->getMaterial(i).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1081 m_meshnode->getMaterial(i).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1082 m_meshnode->getMaterial(i).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1084 } else if (m_prop.visual == "upright_sprite") {
1085 scene::IMesh *mesh = m_meshnode->getMesh();
1087 std::string tname = "unknown_object.png";
1088 if (!m_prop.textures.empty())
1089 tname = m_prop.textures[0];
1091 scene::IMeshBuffer *buf = mesh->getMeshBuffer(0);
1092 buf->getMaterial().setTexture(0,
1093 tsrc->getTextureForMesh(tname));
1095 // This allows setting per-material colors. However, until a real lighting
1096 // system is added, the code below will have no effect. Once MineTest
1097 // has directional lighting, it should work automatically.
1098 if(!m_prop.colors.empty()) {
1099 buf->getMaterial().AmbientColor = m_prop.colors[0];
1100 buf->getMaterial().DiffuseColor = m_prop.colors[0];
1101 buf->getMaterial().SpecularColor = m_prop.colors[0];
1104 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1105 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1106 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1109 std::string tname = "unknown_object.png";
1110 if (m_prop.textures.size() >= 2)
1111 tname = m_prop.textures[1];
1112 else if (!m_prop.textures.empty())
1113 tname = m_prop.textures[0];
1115 scene::IMeshBuffer *buf = mesh->getMeshBuffer(1);
1116 buf->getMaterial().setTexture(0,
1117 tsrc->getTextureForMesh(tname));
1119 // This allows setting per-material colors. However, until a real lighting
1120 // system is added, the code below will have no effect. Once MineTest
1121 // has directional lighting, it should work automatically.
1122 if (m_prop.colors.size() >= 2) {
1123 buf->getMaterial().AmbientColor = m_prop.colors[1];
1124 buf->getMaterial().DiffuseColor = m_prop.colors[1];
1125 buf->getMaterial().SpecularColor = m_prop.colors[1];
1126 } else if (!m_prop.colors.empty()) {
1127 buf->getMaterial().AmbientColor = m_prop.colors[0];
1128 buf->getMaterial().DiffuseColor = m_prop.colors[0];
1129 buf->getMaterial().SpecularColor = m_prop.colors[0];
1132 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1133 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1134 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1140 void GenericCAO::updateAnimation()
1142 if (!m_animated_meshnode)
1145 if (m_animated_meshnode->getStartFrame() != m_animation_range.X ||
1146 m_animated_meshnode->getEndFrame() != m_animation_range.Y)
1147 m_animated_meshnode->setFrameLoop(m_animation_range.X, m_animation_range.Y);
1148 if (m_animated_meshnode->getAnimationSpeed() != m_animation_speed)
1149 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1150 m_animated_meshnode->setTransitionTime(m_animation_blend);
1151 // Requires Irrlicht 1.8 or greater
1152 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR > 1
1153 if (m_animated_meshnode->getLoopMode() != m_animation_loop)
1154 m_animated_meshnode->setLoopMode(m_animation_loop);
1158 void GenericCAO::updateBonePosition()
1160 if(m_bone_position.empty() || !m_animated_meshnode)
1163 m_animated_meshnode->setJointMode(irr::scene::EJUOR_CONTROL); // To write positions to the mesh on render
1164 for(std::unordered_map<std::string, core::vector2d<v3f>>::const_iterator
1165 ii = m_bone_position.begin(); ii != m_bone_position.end(); ++ii) {
1166 std::string bone_name = (*ii).first;
1167 v3f bone_pos = (*ii).second.X;
1168 v3f bone_rot = (*ii).second.Y;
1169 irr::scene::IBoneSceneNode* bone = m_animated_meshnode->getJointNode(bone_name.c_str());
1172 bone->setPosition(bone_pos);
1173 bone->setRotation(bone_rot);
1178 void GenericCAO::updateAttachments()
1181 if (!getParent()) { // Detach or don't attach
1182 scene::ISceneNode *node = getSceneNode();
1184 v3f old_position = node->getAbsolutePosition();
1185 v3f old_rotation = node->getRotation();
1186 node->setParent(m_smgr->getRootSceneNode());
1187 node->setPosition(old_position);
1188 node->setRotation(old_rotation);
1189 node->updateAbsolutePosition();
1191 if (m_is_local_player) {
1192 LocalPlayer *player = m_env->getLocalPlayer();
1193 player->isAttached = false;
1198 scene::ISceneNode *my_node = getSceneNode();
1200 scene::ISceneNode *parent_node = getParent()->getSceneNode();
1201 scene::IAnimatedMeshSceneNode *parent_animated_mesh_node =
1202 getParent()->getAnimatedMeshSceneNode();
1203 if (parent_animated_mesh_node && !m_attachment_bone.empty()) {
1204 parent_node = parent_animated_mesh_node->getJointNode(m_attachment_bone.c_str());
1207 if (my_node && parent_node) {
1208 my_node->setParent(parent_node);
1209 my_node->setPosition(m_attachment_position);
1210 my_node->setRotation(m_attachment_rotation);
1211 my_node->updateAbsolutePosition();
1213 if (m_is_local_player) {
1214 LocalPlayer *player = m_env->getLocalPlayer();
1215 player->isAttached = true;
1220 void GenericCAO::processMessage(const std::string &data)
1222 //infostream<<"GenericCAO: Got message"<<std::endl;
1223 std::istringstream is(data, std::ios::binary);
1225 u8 cmd = readU8(is);
1226 if (cmd == GENERIC_CMD_SET_PROPERTIES) {
1227 m_prop = gob_read_set_properties(is);
1229 m_selection_box = m_prop.collisionbox;
1230 m_selection_box.MinEdge *= BS;
1231 m_selection_box.MaxEdge *= BS;
1233 m_tx_size.X = 1.0 / m_prop.spritediv.X;
1234 m_tx_size.Y = 1.0 / m_prop.spritediv.Y;
1236 if(!m_initial_tx_basepos_set){
1237 m_initial_tx_basepos_set = true;
1238 m_tx_basepos = m_prop.initial_sprite_basepos;
1240 if (m_is_local_player) {
1241 LocalPlayer *player = m_env->getLocalPlayer();
1242 player->makes_footstep_sound = m_prop.makes_footstep_sound;
1243 player->setCollisionbox(m_selection_box);
1246 if ((m_is_player && !m_is_local_player) && m_prop.nametag.empty())
1247 m_prop.nametag = m_name;
1250 } else if (cmd == GENERIC_CMD_UPDATE_POSITION) {
1251 // Not sent by the server if this object is an attachment.
1252 // We might however get here if the server notices the object being detached before the client.
1253 m_position = readV3F1000(is);
1254 m_velocity = readV3F1000(is);
1255 m_acceleration = readV3F1000(is);
1256 if(fabs(m_prop.automatic_rotate) < 0.001)
1257 m_yaw = readF1000(is);
1260 bool do_interpolate = readU8(is);
1261 bool is_end_position = readU8(is);
1262 float update_interval = readF1000(is);
1264 // Place us a bit higher if we're physical, to not sink into
1265 // the ground due to sucky collision detection...
1267 m_position += v3f(0,0.002,0);
1269 if(getParent() != NULL) // Just in case
1274 if(!m_prop.physical)
1275 pos_translator.update(m_position, is_end_position, update_interval);
1277 pos_translator.init(m_position);
1280 } else if (cmd == GENERIC_CMD_SET_TEXTURE_MOD) {
1281 std::string mod = deSerializeString(is);
1283 // immediatly reset a engine issued texture modifier if a mod sends a different one
1284 if (m_reset_textures_timer > 0) {
1285 m_reset_textures_timer = -1;
1286 updateTextures(m_previous_texture_modifier);
1288 updateTextures(mod);
1289 } else if (cmd == GENERIC_CMD_SET_SPRITE) {
1290 v2s16 p = readV2S16(is);
1291 int num_frames = readU16(is);
1292 float framelength = readF1000(is);
1293 bool select_horiz_by_yawpitch = readU8(is);
1296 m_anim_num_frames = num_frames;
1297 m_anim_framelength = framelength;
1298 m_tx_select_horiz_by_yawpitch = select_horiz_by_yawpitch;
1301 } else if (cmd == GENERIC_CMD_SET_PHYSICS_OVERRIDE) {
1302 float override_speed = readF1000(is);
1303 float override_jump = readF1000(is);
1304 float override_gravity = readF1000(is);
1305 // these are sent inverted so we get true when the server sends nothing
1306 bool sneak = !readU8(is);
1307 bool sneak_glitch = !readU8(is);
1308 bool new_move = !readU8(is);
1311 if(m_is_local_player)
1313 LocalPlayer *player = m_env->getLocalPlayer();
1314 player->physics_override_speed = override_speed;
1315 player->physics_override_jump = override_jump;
1316 player->physics_override_gravity = override_gravity;
1317 player->physics_override_sneak = sneak;
1318 player->physics_override_sneak_glitch = sneak_glitch;
1319 player->physics_override_new_move = new_move;
1321 } else if (cmd == GENERIC_CMD_SET_ANIMATION) {
1322 // TODO: change frames send as v2s32 value
1323 v2f range = readV2F1000(is);
1324 if (!m_is_local_player) {
1325 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1326 m_animation_speed = readF1000(is);
1327 m_animation_blend = readF1000(is);
1328 // these are sent inverted so we get true when the server sends nothing
1329 m_animation_loop = !readU8(is);
1332 LocalPlayer *player = m_env->getLocalPlayer();
1333 if(player->last_animation == NO_ANIM)
1335 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1336 m_animation_speed = readF1000(is);
1337 m_animation_blend = readF1000(is);
1338 // these are sent inverted so we get true when the server sends nothing
1339 m_animation_loop = !readU8(is);
1341 // update animation only if local animations present
1342 // and received animation is unknown (except idle animation)
1343 bool is_known = false;
1344 for (int i = 1;i<4;i++)
1346 if(m_animation_range.Y == player->local_animations[i].Y)
1350 (player->local_animations[1].Y + player->local_animations[2].Y < 1))
1355 } else if (cmd == GENERIC_CMD_SET_BONE_POSITION) {
1356 std::string bone = deSerializeString(is);
1357 v3f position = readV3F1000(is);
1358 v3f rotation = readV3F1000(is);
1359 m_bone_position[bone] = core::vector2d<v3f>(position, rotation);
1361 updateBonePosition();
1362 } else if (cmd == GENERIC_CMD_ATTACH_TO) {
1363 u16 parentID = readS16(is);
1364 u16 oldparent = m_env->attachement_parent_ids[getId()];
1366 m_children.erase(std::remove(m_children.begin(), m_children.end(),
1367 getId()), m_children.end());
1369 m_env->attachement_parent_ids[getId()] = parentID;
1370 GenericCAO *parentobj = m_env->getGenericCAO(parentID);
1373 parentobj->m_children.push_back(getId());
1376 m_attachment_bone = deSerializeString(is);
1377 m_attachment_position = readV3F1000(is);
1378 m_attachment_rotation = readV3F1000(is);
1380 // localplayer itself can't be attached to localplayer
1381 if (!m_is_local_player) {
1382 m_attached_to_local = getParent() != NULL && getParent()->isLocalPlayer();
1383 // Objects attached to the local player should be hidden by default
1384 m_is_visible = !m_attached_to_local;
1387 updateAttachments();
1388 } else if (cmd == GENERIC_CMD_PUNCHED) {
1389 /*s16 damage =*/ readS16(is);
1390 s16 result_hp = readS16(is);
1392 // Use this instead of the send damage to not interfere with prediction
1393 s16 damage = m_hp - result_hp;
1401 // TODO: Execute defined fast response
1402 // As there is no definition, make a smoke puff
1403 ClientSimpleObject *simple = createSmokePuff(
1404 m_smgr, m_env, m_position,
1405 m_prop.visual_size * BS);
1406 m_env->addSimpleObject(simple);
1407 } else if (m_reset_textures_timer < 0) {
1408 // TODO: Execute defined fast response
1409 // Flashing shall suffice as there is no definition
1410 m_reset_textures_timer = 0.05;
1412 m_reset_textures_timer += 0.05 * damage;
1413 updateTextures(m_current_texture_modifier + "^[brighten");
1416 } else if (cmd == GENERIC_CMD_UPDATE_ARMOR_GROUPS) {
1417 m_armor_groups.clear();
1418 int armor_groups_size = readU16(is);
1419 for(int i=0; i<armor_groups_size; i++)
1421 std::string name = deSerializeString(is);
1422 int rating = readS16(is);
1423 m_armor_groups[name] = rating;
1425 } else if (cmd == GENERIC_CMD_UPDATE_NAMETAG_ATTRIBUTES) {
1426 // Deprecated, for backwards compatibility only.
1427 readU8(is); // version
1428 m_prop.nametag_color = readARGB8(is);
1429 if (m_nametag != NULL) {
1430 m_nametag->nametag_color = m_prop.nametag_color;
1432 pos.Y = m_prop.collisionbox.MaxEdge.Y + 0.3f;
1433 m_nametag->nametag_pos = pos;
1435 } else if (cmd == GENERIC_CMD_SPAWN_INFANT) {
1436 u16 child_id = readU16(is);
1437 u8 type = readU8(is);
1439 if (GenericCAO *childobj = m_env->getGenericCAO(child_id)) {
1440 childobj->processInitData(deSerializeLongString(is));
1442 m_env->addActiveObject(child_id, type, deSerializeLongString(is));
1445 warningstream << FUNCTION_NAME
1446 << ": unknown command or outdated client \""
1447 << +cmd << "\"" << std::endl;
1451 /* \pre punchitem != NULL
1453 bool GenericCAO::directReportPunch(v3f dir, const ItemStack *punchitem,
1454 float time_from_last_punch)
1456 assert(punchitem); // pre-condition
1457 const ToolCapabilities *toolcap =
1458 &punchitem->getToolCapabilities(m_client->idef());
1459 PunchDamageResult result = getPunchDamage(
1463 time_from_last_punch);
1465 if(result.did_punch && result.damage != 0)
1467 if(result.damage < m_hp)
1469 m_hp -= result.damage;
1472 // TODO: Execute defined fast response
1473 // As there is no definition, make a smoke puff
1474 ClientSimpleObject *simple = createSmokePuff(
1475 m_smgr, m_env, m_position,
1476 m_prop.visual_size * BS);
1477 m_env->addSimpleObject(simple);
1479 // TODO: Execute defined fast response
1480 // Flashing shall suffice as there is no definition
1481 if (m_reset_textures_timer < 0) {
1482 m_reset_textures_timer = 0.05;
1483 if (result.damage >= 2)
1484 m_reset_textures_timer += 0.05 * result.damage;
1485 updateTextures(m_current_texture_modifier + "^[brighten");
1492 std::string GenericCAO::debugInfoText()
1494 std::ostringstream os(std::ios::binary);
1495 os<<"GenericCAO hp="<<m_hp<<"\n";
1497 for(ItemGroupList::const_iterator i = m_armor_groups.begin();
1498 i != m_armor_groups.end(); ++i)
1500 os<<i->first<<"="<<i->second<<", ";
1507 GenericCAO proto_GenericCAO(NULL, NULL);