2
0

MeshComponent.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // ----------------------------------------------------------------
  2. // From Game Programming in C++ by Sanjay Madhav
  3. // Copyright (C) 2017 Sanjay Madhav. All rights reserved.
  4. //
  5. // Released under the BSD License
  6. // See LICENSE in root directory for full details.
  7. // ----------------------------------------------------------------
  8. #include "MeshComponent.h"
  9. #include "Shader.h"
  10. #include "Mesh.h"
  11. #include "Actor.h"
  12. #include "Game.h"
  13. #include "Renderer.h"
  14. #include "Texture.h"
  15. #include "VertexArray.h"
  16. #include "LevelLoader.h"
  17. MeshComponent::MeshComponent(Actor* owner, bool isSkeletal)
  18. :Component(owner)
  19. ,mMesh(nullptr)
  20. ,mTextureIndex(0)
  21. ,mVisible(true)
  22. ,mIsSkeletal(isSkeletal)
  23. {
  24. mOwner->GetGame()->GetRenderer()->AddMeshComp(this);
  25. }
  26. MeshComponent::~MeshComponent()
  27. {
  28. mOwner->GetGame()->GetRenderer()->RemoveMeshComp(this);
  29. }
  30. void MeshComponent::Draw(Shader* shader)
  31. {
  32. if (mMesh)
  33. {
  34. // Set the world transform
  35. shader->SetMatrixUniform("uWorldTransform",
  36. mOwner->GetWorldTransform());
  37. // Set specular power
  38. shader->SetFloatUniform("uSpecPower", mMesh->GetSpecPower());
  39. // Set the active texture
  40. Texture* t = mMesh->GetTexture(mTextureIndex);
  41. if (t)
  42. {
  43. t->SetActive();
  44. }
  45. // Set the mesh's vertex array as active
  46. VertexArray* va = mMesh->GetVertexArray();
  47. va->SetActive();
  48. // Draw
  49. glDrawElements(GL_TRIANGLES, va->GetNumIndices(), GL_UNSIGNED_INT, nullptr);
  50. }
  51. }
  52. void MeshComponent::LoadProperties(const rapidjson::Value& inObj)
  53. {
  54. Component::LoadProperties(inObj);
  55. std::string meshFile;
  56. if (JsonHelper::GetString(inObj, "meshFile", meshFile))
  57. {
  58. SetMesh(mOwner->GetGame()->GetRenderer()->GetMesh(meshFile));
  59. }
  60. int idx;
  61. if (JsonHelper::GetInt(inObj, "textureIndex", idx))
  62. {
  63. mTextureIndex = static_cast<size_t>(idx);
  64. }
  65. JsonHelper::GetBool(inObj, "visible", mVisible);
  66. JsonHelper::GetBool(inObj, "isSkeletal", mIsSkeletal);
  67. }
  68. void MeshComponent::SaveProperties(rapidjson::Document::AllocatorType& alloc, rapidjson::Value& inObj) const
  69. {
  70. Component::SaveProperties(alloc, inObj);
  71. if (mMesh)
  72. {
  73. JsonHelper::AddString(alloc, inObj, "meshFile", mMesh->GetFileName());
  74. }
  75. JsonHelper::AddInt(alloc, inObj, "textureIndex", static_cast<int>(mTextureIndex));
  76. JsonHelper::AddBool(alloc, inObj, "visible", mVisible);
  77. JsonHelper::AddBool(alloc, inObj, "isSkeletal", mIsSkeletal);
  78. }