-
Notifications
You must be signed in to change notification settings - Fork 389
Expand file tree
/
Copy pathSpriteComponent.cpp
More file actions
90 lines (76 loc) · 2.3 KB
/
SpriteComponent.cpp
File metadata and controls
90 lines (76 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// ----------------------------------------------------------------
// From Game Programming in C++ by Sanjay Madhav
// Copyright (C) 2017 Sanjay Madhav. All rights reserved.
//
// Released under the BSD License
// See LICENSE in root directory for full details.
// ----------------------------------------------------------------
#include "SpriteComponent.h"
#include "Texture.h"
#include "Shader.h"
#include "Actor.h"
#include "Game.h"
#include "Renderer.h"
#include "LevelLoader.h"
SpriteComponent::SpriteComponent(Actor* owner, int drawOrder)
:Component(owner)
,mTexture(nullptr)
,mDrawOrder(drawOrder)
,mTexWidth(0)
,mTexHeight(0)
,mVisible(true)
{
mOwner->GetGame()->GetRenderer()->AddSprite(this);
}
SpriteComponent::~SpriteComponent()
{
mOwner->GetGame()->GetRenderer()->RemoveSprite(this);
}
void SpriteComponent::Draw(Shader* shader)
{
if (mTexture)
{
// Scale the quad by the width/height of texture
Matrix4 scaleMat = Matrix4::CreateScale(
static_cast<float>(mTexWidth),
static_cast<float>(mTexHeight),
1.0f);
Matrix4 world = scaleMat * mOwner->GetWorldTransform();
// Since all sprites use the same shader/vertices,
// the game first sets them active before any sprite draws
// Set world transform
shader->SetMatrixUniform("uWorldTransform", world);
// Set current texture
mTexture->SetActive();
// Draw quad
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);
}
}
void SpriteComponent::SetTexture(Texture* texture)
{
mTexture = texture;
// Set width/height
mTexWidth = texture->GetWidth();
mTexHeight = texture->GetHeight();
}
void SpriteComponent::LoadProperties(const rapidjson::Value& inObj)
{
Component::LoadProperties(inObj);
std::string texFile;
if (JsonHelper::GetString(inObj, "textureFile", texFile))
{
SetTexture(mOwner->GetGame()->GetRenderer()->GetTexture(texFile));
}
JsonHelper::GetInt(inObj, "drawOrder", mDrawOrder);
JsonHelper::GetBool(inObj, "visible", mVisible);
}
void SpriteComponent::SaveProperties(rapidjson::Document::AllocatorType& alloc, rapidjson::Value& inObj) const
{
Component::SaveProperties(alloc, inObj);
if (mTexture)
{
JsonHelper::AddString(alloc, inObj, "textureFile", mTexture->GetFileName());
}
JsonHelper::AddInt(alloc, inObj, "drawOrder", mDrawOrder);
JsonHelper::AddBool(alloc, inObj, "visible", mVisible);
}