EntityModel.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. /*
  2. * Copyright (C) 2022 The V-Gears Team
  3. *
  4. * This file is part of V-Gears
  5. *
  6. * V-Gears is free software: you can redistribute it and/or modify it under
  7. * terms of the GNU General Public License as published by the Free Software
  8. * Foundation, version 3.0 (GPLv3) of the License.
  9. *
  10. * V-Gears 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 General Public License for more details.
  14. */
  15. #include <iostream>
  16. #include <algorithm>
  17. #include <vector>
  18. #include <OgreEntity.h>
  19. #include <OgreSubEntity.h>
  20. #include <OgreBone.h>
  21. #include <OgreSkeletonInstance.h>
  22. #include <OgreMaterialManager.h>
  23. #include <OgreResourceGroupManager.h>
  24. #include <OgreTechnique.h>
  25. #include <OgrePass.h>
  26. #include <OgreRoot.h>
  27. #include <OgreTextureManager.h>
  28. #include <OgreHardwarePixelBuffer.h>
  29. #include "core/EntityModel.h"
  30. #include "core/EntityManager.h"
  31. #include "core/Logger.h"
  32. #include "core/Timer.h"
  33. EntityModel::EntityModel(
  34. const Ogre::String& name, const Ogre::String file_name, Ogre::SceneNode* node,
  35. const Ogre::String& resource_group
  36. ): Entity(name, node), animation_current_(nullptr)
  37. {
  38. Ogre::SceneManager* scene_manager;
  39. Ogre::String res_group = resource_group;
  40. if (res_group.empty()){
  41. switch(EntityManager::getSingleton().GetModule()){
  42. case Manager::BATTLE:
  43. res_group = "BATTLE_MODELS";
  44. break;
  45. case Manager::WORLD:
  46. res_group = "WORLD_MODELS";
  47. break;
  48. case Manager::FIELD:
  49. default:
  50. res_group = "FIELD_MODELS";
  51. }
  52. }
  53. scene_manager = Ogre::Root::getSingleton().getSceneManager("Scene");
  54. resource_group_ = res_group;
  55. model_ = scene_manager->createEntity(name_, file_name, res_group);
  56. model_->setVisible(false);
  57. PlayAnimation(animation_default_, Entity::AUTO_ANIMATION, Entity::PLAY_LOOPED, 0, -1);
  58. model_node_->attachObject(model_);
  59. }
  60. EntityModel::~EntityModel(){
  61. ScriptAttachModel("", -1, 0.0f, 0.0f, 0.0f);
  62. Ogre::Root::getSingleton().getSceneManager("Scene")->destroyEntity(model_);
  63. }
  64. void EntityModel::Update(){
  65. if (animation_auto_play_ == true) UpdateAnimation(Timer::getSingleton().GetGameTimeDelta());
  66. Entity::Update();
  67. }
  68. void EntityModel::SetVisible(const bool visible){
  69. model_->setVisible(visible);
  70. if (attached_model_ != nullptr) attached_model_->setVisible(visible);
  71. }
  72. bool EntityModel::IsVisible() const{return model_->isVisible();}
  73. float EntityModel::GetAnimationLength(const Ogre::String& animation) const{
  74. Ogre::AnimationStateSet* states = model_->getAllAnimationStates();
  75. if (states == nullptr || states->hasAnimationState(animation) == false) return 0.0f;
  76. return states->getAnimationState(animation)->getLength();
  77. }
  78. unsigned int EntityModel::GetAnimationCount() const{
  79. Ogre::AnimationStateSet* states = model_->getAllAnimationStates();
  80. if (states == nullptr) return 0;
  81. return states->getAnimationStates().size();
  82. }
  83. Ogre::Entity* EntityModel::GetModel(){return model_;}
  84. Ogre::MaterialPtr EntityModel::OwnMaterial(Ogre::SubEntity* sub_entity){
  85. Ogre::MaterialPtr material = sub_entity->getMaterial();
  86. if (std::find(own_materials_.begin(), own_materials_.end(), material->getName()) == own_materials_.end()){
  87. const Ogre::String own_name = material->getName() + "/" + name_;
  88. Ogre::MaterialPtr own = Ogre::MaterialManager::getSingleton().getByName(own_name, material->getGroup());
  89. if (own == nullptr) own = material->clone(own_name);
  90. own_materials_.push_back(own_name);
  91. sub_entity->setMaterial(own);
  92. material = own;
  93. }
  94. return material;
  95. }
  96. void EntityModel::ScriptSetTexture(const char* texture){
  97. const Ogre::String image(texture);
  98. Ogre::String group;
  99. if (Ogre::ResourceGroupManager::getSingleton().resourceExists("BATTLE_MODELS", image)) group = "BATTLE_MODELS";
  100. else if (Ogre::ResourceGroupManager::getSingleton().resourceExists("IMAGES", image)) group = "IMAGES";
  101. else{
  102. LOG_WARNING("Image '" + image + "' for the model '" + name_ + "' doesn't exist.");
  103. return;
  104. }
  105. Ogre::TexturePtr loaded = Ogre::TextureManager::getSingleton().load(image, group);
  106. for (unsigned int s = 0; s < model_->getNumSubEntities(); ++ s){
  107. Ogre::MaterialPtr material = OwnMaterial(model_->getSubEntity(s));
  108. for (unsigned short t = 0; t < material->getNumTechniques(); ++ t){
  109. Ogre::Technique* technique = material->getTechnique(t);
  110. for (unsigned short p = 0; p < technique->getNumPasses(); ++ p){
  111. Ogre::Pass* pass = technique->getPass(p);
  112. pass->removeAllTextureUnitStates();
  113. pass->createTextureUnitState()->setTexture(loaded);
  114. pass->setLightingEnabled(false);
  115. }
  116. }
  117. }
  118. }
  119. std::tuple<float, float, float> EntityModel::ScriptGetBonePosition(const int bone){
  120. Ogre::SkeletonInstance* skeleton = model_->getSkeleton();
  121. const Ogre::String name = "bone" + std::to_string(bone);
  122. if (skeleton == nullptr || !skeleton->hasBone(name)) return std::make_tuple(0.0f, 0.0f, 0.0f);
  123. // Bring the skeleton to the current frame of the animation.
  124. model_->_updateAnimation();
  125. const Ogre::Vector3 position
  126. = model_->_getParentNodeFullTransform() * skeleton->getBone(name)->_getDerivedPosition();
  127. return std::make_tuple(position.x, position.y, position.z);
  128. }
  129. bool EntityModel::ScriptAttachModel(
  130. const char* model, const int bone, const float rx, const float ry, const float rz
  131. ){
  132. Ogre::SceneManager* scene_manager = Ogre::Root::getSingleton().getSceneManager("Scene");
  133. if (attached_model_ != nullptr){
  134. model_->detachObjectFromBone(attached_model_);
  135. scene_manager->destroyEntity(attached_model_);
  136. attached_model_ = nullptr;
  137. }
  138. const Ogre::String file(model);
  139. if (file.empty()) return true;
  140. Ogre::SkeletonInstance* skeleton = model_->getSkeleton();
  141. if (skeleton == nullptr){
  142. LOG_WARNING("The model '" + name_ + "' has no skeleton to attach '" + file + "' to.");
  143. return false;
  144. }
  145. // Bones are called bone0, bone1... and the skeleton also has a root bone.
  146. const int bone_number = (bone >= 0) ? bone : static_cast<int>(skeleton->getNumBones()) - 2;
  147. const Ogre::String bone_name = "bone" + std::to_string(bone_number);
  148. if (!skeleton->hasBone(bone_name)){
  149. LOG_WARNING("The model '" + name_ + "' has no bone '" + bone_name + "'.");
  150. return false;
  151. }
  152. if (!Ogre::ResourceGroupManager::getSingleton().resourceExists(resource_group_, file)){
  153. LOG_WARNING("The model '" + file + "' to attach to '" + name_ + "' doesn't exist.");
  154. return false;
  155. }
  156. attached_model_ = scene_manager->createEntity(name_ + "/" + bone_name + "/" + file, file, resource_group_);
  157. // The vertices of an exported model already include the orientation of the root of its skeleton, the
  158. // same one the bone of this skeleton has. Undo it, or it would be applied twice.
  159. Ogre::Quaternion offset = Ogre::Quaternion::IDENTITY;
  160. Ogre::SkeletonInstance* attached_skeleton = attached_model_->getSkeleton();
  161. if (attached_skeleton != nullptr && attached_skeleton->hasBone("root")){
  162. offset = attached_skeleton->getBone("root")->getOrientation().Inverse();
  163. }
  164. // Extra rotation around the axes of the model itself (the ones of the original files).
  165. const Ogre::Quaternion extra
  166. = Ogre::Quaternion(Ogre::Degree(rx), Ogre::Vector3::UNIT_X)
  167. * Ogre::Quaternion(Ogre::Degree(ry), Ogre::Vector3::UNIT_Y)
  168. * Ogre::Quaternion(Ogre::Degree(rz), Ogre::Vector3::UNIT_Z);
  169. offset = extra * offset;
  170. model_->attachObjectToBone(bone_name, attached_model_, offset);
  171. attached_model_->setVisible(model_->isVisible());
  172. return true;
  173. }
  174. void EntityModel::ScriptSetBlend(const int blend){
  175. if (blend == blend_) return;
  176. blend_ = blend;
  177. // The model held in a bone (a weapon) is drawn like the body.
  178. std::vector<Ogre::Entity*> entities {model_};
  179. if (attached_model_ != nullptr) entities.push_back(attached_model_);
  180. for (Ogre::Entity* entity : entities)
  181. for (unsigned int s = 0; s < entity->getNumSubEntities(); ++ s){
  182. Ogre::SubEntity* sub_entity = entity->getSubEntity(s);
  183. // Materials are shared among all the entities of a mesh, so use one of its own.
  184. Ogre::MaterialPtr material = OwnMaterial(sub_entity);
  185. for (unsigned short t = 0; t < material->getNumTechniques(); ++ t){
  186. Ogre::Technique* technique = material->getTechnique(t);
  187. for (unsigned short p = 0; p < technique->getNumPasses(); ++ p){
  188. Ogre::Pass* pass = technique->getPass(p);
  189. switch (blend){
  190. case BLEND_ADDITIVE:
  191. pass->setSceneBlending(Ogre::SBT_ADD);
  192. pass->setDepthWriteEnabled(false);
  193. pass->setLightingEnabled(false);
  194. break;
  195. case BLEND_ALPHA:
  196. pass->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);
  197. pass->setDepthWriteEnabled(false);
  198. pass->setLightingEnabled(false);
  199. break;
  200. default:
  201. pass->setSceneBlending(Ogre::SBT_REPLACE);
  202. pass->setDepthWriteEnabled(true);
  203. }
  204. }
  205. }
  206. }
  207. }
  208. /**
  209. * Gets a texture of one white pixel, for the parts that have no texture (they only have the colours of
  210. * the vertices), so a texture unit can give them an opacity.
  211. */
  212. static Ogre::TexturePtr GetWhiteTexture(){
  213. const Ogre::String name = "vgears_white_1x1";
  214. Ogre::TextureManager& manager = Ogre::TextureManager::getSingleton();
  215. Ogre::TexturePtr texture = manager.getByName(name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
  216. if (texture != nullptr) return texture;
  217. texture = manager.createManual(
  218. name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D, 1, 1, 0, Ogre::PF_BYTE_RGBA
  219. );
  220. unsigned char pixel[4] = {255, 255, 255, 255};
  221. Ogre::PixelBox box(Ogre::Box(0, 0, 1, 1), Ogre::PF_BYTE_RGBA, pixel);
  222. texture->getBuffer()->blitFromMemory(box);
  223. return texture;
  224. }
  225. void EntityModel::ScriptSetAlpha(const float alpha){
  226. if (blend_ == BLEND_NORMAL) return;
  227. const float a = std::max(0.0f, std::min(1.0f, alpha));
  228. std::vector<Ogre::Entity*> entities {model_};
  229. if (attached_model_ != nullptr) entities.push_back(attached_model_);
  230. for (Ogre::Entity* entity : entities)
  231. for (unsigned int s = 0; s < entity->getNumSubEntities(); ++ s){
  232. Ogre::MaterialPtr material = entity->getSubEntity(s)->getMaterial();
  233. for (unsigned short t = 0; t < material->getNumTechniques(); ++ t){
  234. Ogre::Technique* technique = material->getTechnique(t);
  235. for (unsigned short p = 0; p < technique->getNumPasses(); ++ p){
  236. Ogre::Pass* pass = technique->getPass(p);
  237. // Parts with only vertex colours have no texture unit to change, so give them a white one.
  238. if (pass->getNumTextureUnitStates() == 0) pass->createTextureUnitState()->setTexture(GetWhiteTexture());
  239. for (unsigned short u = 0; u < pass->getNumTextureUnitStates(); ++ u){
  240. Ogre::TextureUnitState* unit = pass->getTextureUnitState(u);
  241. if (blend_ == BLEND_ADDITIVE){
  242. // The colour is added, so less brightness is less opacity.
  243. unit->setColourOperationEx(
  244. Ogre::LBX_MODULATE, Ogre::LBS_TEXTURE, Ogre::LBS_MANUAL,
  245. Ogre::ColourValue::White, Ogre::ColourValue(a, a, a)
  246. );
  247. }
  248. else{
  249. unit->setAlphaOperation(
  250. Ogre::LBX_MODULATE, Ogre::LBS_TEXTURE, Ogre::LBS_MANUAL, 1.0f, a
  251. );
  252. }
  253. }
  254. }
  255. }
  256. }
  257. }
  258. void EntityModel::ReleaseResources(){
  259. // The materials are used by the model, so make it use none before removing them.
  260. for (const Ogre::String& name : own_materials_){
  261. // The group is not known here (the material has the one of the original), so search all.
  262. Ogre::MaterialManager& manager = Ogre::MaterialManager::getSingleton();
  263. Ogre::MaterialPtr material = manager.getByName(
  264. name, Ogre::ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME
  265. );
  266. if (material != nullptr) manager.remove(material);
  267. }
  268. own_materials_.clear();
  269. }
  270. void EntityModel::PlayAnimation(
  271. const Ogre::String& animation, Entity::AnimationState state,
  272. Entity::AnimationPlayType play_type, const float start, const float end
  273. ){
  274. if (animation_current_ != nullptr) animation_current_->setEnabled(false);
  275. if (
  276. model_->getAllAnimationStates() != nullptr
  277. && model_->getAllAnimationStates()->hasAnimationState(animation) == true
  278. ){
  279. animation_current_name_ = animation;
  280. animation_current_ = model_->getAnimationState(animation);
  281. animation_current_->setLoop((play_type == Entity::PLAY_LOOPED) ? true : false);
  282. // Single frame animations have no length. A looping animation without length wraps its
  283. // time position dividing by zero, ends up with a time that is not a number, and never
  284. // finishes, so any script waiting for it would wait forever.
  285. if (animation_current_->getLength() <= 0.0f) animation_current_->setLoop(false);
  286. animation_current_->setEnabled(true);
  287. animation_current_->setTimePosition(
  288. (start == -1) ? animation_current_->getLength() : start
  289. );
  290. animation_end_time_ = (end == -1) ? animation_current_->getLength() : end;
  291. animation_state_ = state;
  292. animation_play_type_ = play_type;
  293. }
  294. else{
  295. // Idle is hard coded to the default animation,
  296. // so don't spam crazy amounts of errors if its not found.
  297. if (animation != "Idle"){
  298. LOG_ERROR(
  299. "Animation '" + animation + "' doesn't exist in model '" + model_->getName() + "'."
  300. );
  301. }
  302. }
  303. }
  304. void EntityModel::PlayAnimationContinue(const Ogre::String& animation){
  305. if (
  306. // If animation isn't being played...
  307. animation_current_ == nullptr
  308. // ... the animatio to play exists (use this to avoid exception)...
  309. || (model_->getAllAnimationStates()->hasAnimationState(animation) == true
  310. && (
  311. // and (the requested animation is not currently playing...
  312. animation_current_ != model_->getAnimationState(animation)
  313. // or it's currently playing but it's not looped)
  314. || animation_play_type_ != Entity::PLAY_LOOPED))
  315. ){
  316. PlayAnimation(animation, Entity::AUTO_ANIMATION, Entity::PLAY_LOOPED, 0, -1);
  317. }
  318. }
  319. void EntityModel::UpdateAnimation(const float delta){
  320. if (animation_current_ != nullptr){
  321. float delta_mod = delta * animation_speed_;
  322. bool stop_check
  323. = (animation_current_->hasEnded() == true)
  324. || (animation_current_->getTimePosition() + delta_mod >= animation_end_time_);
  325. if (stop_check == true){
  326. //LOG_TRIVIAL("Animation finished for entity \"" + name_ + "\".");
  327. for (size_t i = 0; i < animation_sync_.size(); ++ i)
  328. ScriptManager::getSingleton().ContinueScriptExecution(animation_sync_[i]);
  329. animation_sync_.clear();
  330. if (animation_play_type_ == Entity::PLAY_DEFAULT){
  331. float time = (animation_current_->hasEnded() != true)
  332. ? animation_current_->getTimePosition() : 0;
  333. PlayAnimation(
  334. animation_default_, Entity::AUTO_ANIMATION, Entity::PLAY_LOOPED, time, -1
  335. );
  336. animation_current_->addTime(delta_mod);
  337. }
  338. else if (animation_play_type_ == Entity::PLAY_LOOPED){
  339. float time = (animation_current_->hasEnded() != true)
  340. ? animation_current_->getTimePosition()
  341. : animation_current_->getTimePosition() - animation_current_->getLength();
  342. PlayAnimation(
  343. animation_current_name_, Entity::AUTO_ANIMATION, Entity::PLAY_LOOPED, time, -1
  344. );
  345. animation_current_->addTime(delta_mod);
  346. }
  347. }
  348. else animation_current_->addTime(delta_mod);
  349. }
  350. }