ModelMaterials.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. #pragma once
  16. #include <OgreMaterial.h>
  17. #include <OgreMaterialManager.h>
  18. #include <OgreMesh.h>
  19. #include <OgreSubMesh.h>
  20. #include <string>
  21. /**
  22. * Gives a mesh its own copy of each of its materials.
  23. *
  24. * The original game names the materials of many unrelated models the same ("gzbb/0" is both a field model and a
  25. * battle enemy), but Ogre keeps all materials in a single namespace. Converting the models changes their materials
  26. * (texture names...), so a material shared by name was changed by one model under the feet of the next, and the
  27. * exported material scripts of different models defined the same material twice.
  28. *
  29. * Every sub mesh material is replaced by a copy named "<owner>/<original name>", which is unique to the model. It
  30. * must be called before the mesh is exported, so the exported mesh refers to the new names.
  31. *
  32. * @param[in] mesh The mesh.
  33. * @param[in] owner Name that identifies the model, used as prefix.
  34. */
  35. inline void MakeMaterialsUnique(const Ogre::MeshPtr& mesh, const std::string& owner){
  36. if (mesh.isNull()) return;
  37. const std::string prefix = owner + "/";
  38. Ogre::MaterialManager& manager = Ogre::MaterialManager::getSingleton();
  39. for (Ogre::SubMesh* sub_mesh : mesh->getSubMeshes()){
  40. const std::string name = sub_mesh->getMaterialName();
  41. // Already done (the mesh is exported more than once or reused).
  42. if (name.compare(0, prefix.size(), prefix) == 0) continue;
  43. Ogre::MaterialPtr material = manager.getByName(name);
  44. if (material.isNull()) continue;
  45. const std::string unique_name = prefix + name;
  46. if (manager.getByName(unique_name).isNull()) material->clone(unique_name);
  47. sub_mesh->setMaterialName(unique_name);
  48. }
  49. }