PointLightComponent.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 "PointLightComponent.h"
  9. #include "Shader.h"
  10. #include "Game.h"
  11. #include "Renderer.h"
  12. #include "Mesh.h"
  13. #include "VertexArray.h"
  14. #include "Actor.h"
  15. #include "LevelLoader.h"
  16. PointLightComponent::PointLightComponent(Actor* owner)
  17. :Component(owner)
  18. {
  19. owner->GetGame()->GetRenderer()->AddPointLight(this);
  20. }
  21. PointLightComponent::~PointLightComponent()
  22. {
  23. mOwner->GetGame()->GetRenderer()->RemovePointLight(this);
  24. }
  25. void PointLightComponent::Draw(Shader* shader, Mesh* mesh)
  26. {
  27. // We assume, coming into this function, that the shader is active
  28. // and the sphere mesh is active
  29. // World transform is scaled to the outer radius (divided by the mesh radius)
  30. // and positioned to the world position
  31. Matrix4 scale = Matrix4::CreateScale(mOwner->GetScale() *
  32. mOuterRadius / mesh->GetRadius());
  33. Matrix4 trans = Matrix4::CreateTranslation(mOwner->GetPosition());
  34. Matrix4 worldTransform = scale * trans;
  35. shader->SetMatrixUniform("uWorldTransform", worldTransform);
  36. // Set point light shader constants
  37. shader->SetVectorUniform("uPointLight.mWorldPos", mOwner->GetPosition());
  38. shader->SetVectorUniform("uPointLight.mDiffuseColor", mDiffuseColor);
  39. shader->SetFloatUniform("uPointLight.mInnerRadius", mInnerRadius);
  40. shader->SetFloatUniform("uPointLight.mOuterRadius", mOuterRadius);
  41. // Draw the sphere
  42. glDrawElements(GL_TRIANGLES, mesh->GetVertexArray()->GetNumIndices(),
  43. GL_UNSIGNED_INT, nullptr);
  44. }
  45. void PointLightComponent::LoadProperties(const rapidjson::Value& inObj)
  46. {
  47. Component::LoadProperties(inObj);
  48. JsonHelper::GetVector3(inObj, "color", mDiffuseColor);
  49. JsonHelper::GetFloat(inObj, "innerRadius", mInnerRadius);
  50. JsonHelper::GetFloat(inObj, "outerRadius", mOuterRadius);
  51. }
  52. void PointLightComponent::SaveProperties(rapidjson::Document::AllocatorType& alloc, rapidjson::Value& inObj) const
  53. {
  54. JsonHelper::AddVector3(alloc, inObj, "color", mDiffuseColor);
  55. JsonHelper::AddFloat(alloc, inObj, "innerRadius", mInnerRadius);
  56. JsonHelper::AddFloat(alloc, inObj, "outerRadius", mOuterRadius);
  57. }