-
Notifications
You must be signed in to change notification settings - Fork 1
/
component.go
394 lines (350 loc) · 11.3 KB
/
component.go
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
package engosdl
import (
"encoding/json"
"fmt"
"github.com/veandco/go-sdl2/sdl"
)
// IComponent represents the interface for any component to be added to any
// Entity
type IComponent interface {
IObject
AddDelegateToRegister(IDelegate, IEntity, IComponent, TDelegateSignature) IComponent
DefaultAddDelegateToRegister()
DefaultOnCollision(...interface{}) bool
DefaultOnDestroy(...interface{}) bool
DefaultOnLoad(...interface{}) bool
DefaultOnOutOfBounds(...interface{}) bool
DoDestroy()
DoDump(IComponent)
DoFrameEnd()
DoFrameStart() bool
DoLoad(IComponent) bool
DoUnLoad()
GetActive() bool
GetCache(string) (interface{}, error)
GetDelegate() IDelegate
GetEntity() IEntity
GetRemoveOnDestroy() bool
OnAwake()
OnEnable()
OnRender()
OnStart()
OnUpdate()
RemoveDelegateToRegister(IDelegate, IEntity, IComponent) error
SetActive(bool)
SetCache(string, interface{})
SetCustomOnUpdate(func(IComponent))
SetDelegate(IDelegate)
SetEntity(IEntity)
SetRemoveOnDestroy(bool)
Unmarshal(map[string]interface{})
}
// ICollisionBox represets the interface for any collider collision box.
type ICollisionBox interface {
GetRect() *Rect
GetCenter() *Vector
GetRadius() float64
}
// ICollider represents a special kind of component that implement collisions.
type ICollider interface {
IComponent
GetCollisionBox() ICollisionBox
}
// ISprite represents the interface for any sprite component.
type ISprite interface {
IComponent
GetCamera() *Rect
GetFileImageIndex() int
GetFilename() []string
LoadSprite()
GetSpriteIndex() int
NextFileImage() int
NextSprite() int
PreviousFileImage() int
PreviousSprite() int
SetCamera(*Rect)
}
// ISound represents the interface for any sound component.
type ISound interface {
IComponent
LoadSound()
Play(int)
}
// IText represents the interface for any text component.
type IText interface {
IComponent
SetFontFilename(string) IText
SetColor(sdl.Color) IText
SetMessage(string) IText
}
// IButton represents the interface for any button component.
type IButton interface {
IComponent
SetFontFilename(string) IButton
SetColor(sdl.Color) IButton
SetMessage(string) IButton
}
// ITimer represents the timer component. Timer should be base in engine
// frames.
type ITimer interface {
IComponent
GetTick() int
SetTick(int)
GetTimes() int
SetTimes(int)
}
// Component represents the default IComponent implementation.
type Component struct {
*Object
entity IEntity
active bool
delegate IDelegate
registers []IRegister
removeOnDestroy bool
customOnUpdate func(IComponent)
cache map[string]interface{}
}
var _ IComponent = (*Component)(nil)
// NewComponent creates a new component instance.
func NewComponent(name string) *Component {
Logger.Trace().Str("component", name).Msg("new component")
return &Component{
Object: NewObject(name),
entity: nil,
active: true,
delegate: nil,
registers: []IRegister{},
removeOnDestroy: true,
customOnUpdate: nil,
cache: make(map[string]interface{}),
}
}
// AddDelegateToRegister adds a new delegate that component should register.
func (c *Component) AddDelegateToRegister(delegate IDelegate, entity IEntity, component IComponent, signature TDelegateSignature) IComponent {
Logger.Trace().Str("component", c.GetName()).Msg("AddDelegateToRegister")
register := NewRegister("new-register", c, entity, component, delegate, signature)
c.registers = append(c.registers, register)
return c
}
// DefaultAddDelegateToRegister will proceed to add default delegate to
// register for the component.
func (c *Component) DefaultAddDelegateToRegister() {
}
// DefaultOnCollision is the component default callback when on collision
// delegate is triggered.
func (c *Component) DefaultOnCollision(...interface{}) bool {
return true
}
// DefaultOnDestroy is the component default callback when on destroy delegate
// is triggered.
func (c *Component) DefaultOnDestroy(...interface{}) bool {
return true
}
// DefaultOnLoad is the component default callback when on load delegate is
// triggered.
func (c *Component) DefaultOnLoad(...interface{}) bool {
return true
}
// DefaultOnOutOfBounds is the component default callback when on load delegate
// is triggered.
func (c *Component) DefaultOnOutOfBounds(...interface{}) bool {
return true
}
// DoDestroy calls all methods to clean up component.
func (c *Component) DoDestroy() {
Logger.Trace().Str("component", c.GetName()).Msg("DoDestroy")
// Deregister all register entries from delegate handler
for _, register := range c.registers {
GetDelegateManager().DeregisterFromDelegate(register.GetRegisterID())
register.SetDelegate(nil)
}
// Delete delegate being created.
if c.GetDelegate() != nil {
GetDelegateManager().DeleteDelegate(c.GetDelegate())
}
c.registers = []IRegister{}
c.delegate = nil
c.SetLoaded(false)
c.SetStarted(false)
}
// DoDump dumps component in JSON format.
func (c *Component) DoDump(component IComponent) {
if result, err := json.Marshal(component); err == nil {
fmt.Printf("%s\n", result)
}
}
// DoFrameEnd calls all methods to run at the end of a tick frame.
func (c *Component) DoFrameEnd() {
}
// DoFrameStart calls all methods to run at the start of a tick frame.
func (c *Component) DoFrameStart() bool {
return c.GetStarted()
}
// DoLoad is called when component is loaded by the entity.
func (c *Component) DoLoad(component IComponent) bool {
Logger.Trace().Str("component", c.GetName()).Msg("DoLoad")
// fmt.Printf("load: %#v\n", reflect.TypeOf(component).String())
// component.OnStart()
return c.GetLoaded()
}
// DoUnLoad is called when component is unloaded by the entity. If this method
// is overwritten in any child class, Component method has to be called,
// because it is in charge to deregister all delegates and registers.
func (c *Component) DoUnLoad() {
Logger.Trace().Str("component", c.GetName()).Msg("DoUnLoad")
// Deregister all register entries from delegate handler
for _, register := range c.registers {
GetDelegateManager().DeregisterFromDelegate(register.GetRegisterID())
// Register is created based on delegates for those belonging to the
// DelegateManager. Those are unchanged and delegate does not have to
// be cleared.
if register.GetDelegate() != nil &&
register.GetDelegate().GetID() != GetDelegateManager().GetCollisionDelegate().GetID() &&
register.GetDelegate().GetID() != GetDelegateManager().GetDestroyDelegate().GetID() &&
register.GetDelegate().GetID() != GetDelegateManager().GetLoadDelegate().GetID() {
register.SetDelegate(nil)
}
}
// Delete delegate being created.
if c.GetDelegate() != nil {
GetDelegateManager().DeleteDelegate(c.GetDelegate())
}
c.SetLoaded(false)
c.SetStarted(false)
}
// GetActive returns if component is active or not
func (c *Component) GetActive() bool {
return c.active
}
// GetCache retrieves component cache data for the given key.
func (c *Component) GetCache(key string) (interface{}, error) {
if data, ok := c.cache[key]; ok {
return data, nil
}
return nil, fmt.Errorf("no cache data found for key: %s", key)
}
// GetDelegate returns delegates created by the component.
func (c *Component) GetDelegate() IDelegate {
return c.delegate
}
// GetEntity return the component entity parent.
func (c *Component) GetEntity() IEntity {
return c.entity
}
// GetRemoveOnDestroy returns component remove on destroy. If this attribute
// is true, the component will be removed from the entity when scene is
// fully unloaded.
func (c *Component) GetRemoveOnDestroy() bool {
return c.removeOnDestroy
}
// OnAwake should create all component resources that don't have any dependency
// with any other component or entity.
func (c *Component) OnAwake() {
Logger.Trace().Str("component", c.GetName()).Msg("OnAwake")
c.SetLoaded(true)
}
// OnEnable is called every time the component is enabled.
func (c *Component) OnEnable() {
Logger.Trace().Str("component", c.GetName()).Msg("OnEnable")
}
// OnRender is called for every render tick.
func (c *Component) OnRender() {
// Logger.Trace().Str("component", c.GetName()).Msg("OnRender")
}
// OnStart is called first time the component is enabled.
func (c *Component) OnStart() {
Logger.Trace().Str("component", c.GetName()).Msg("OnStart")
if !c.GetStarted() {
for _, register := range c.registers {
delegate := register.GetDelegate()
// Retrieve delegate from entity and component provided.
if delegate == nil {
entity := register.GetEntity()
if entity == nil {
entity = c.GetEntity()
}
if component := entity.GetComponent(register.GetComponent()); component != nil {
if delegate = component.GetDelegate(); delegate != nil {
register.SetDelegate(delegate)
}
}
}
if delegate != nil {
if registerID, ok := GetDelegateManager().RegisterToDelegate(c, delegate, register.GetSignature()); ok {
register.SetRegisterID(registerID)
continue
}
}
Logger.Error().Err(fmt.Errorf("register for component %s failed", c.GetName())).Str("component", c.GetName()).Msg("registration error")
// panic("Failure at register " + register.GetName())
}
c.SetStarted(true)
}
}
// OnUpdate is called for every update tick.
func (c *Component) OnUpdate() {
// Logger.Trace().Str("component", c.GetName()).Msg("OnUpdate")
if c.customOnUpdate != nil {
c.customOnUpdate(c)
}
}
// RemoveDelegateToRegister removes a register for the given delegate in
// delegate handler. Register is being removed from the component too.
func (c *Component) RemoveDelegateToRegister(delegate IDelegate, entity IEntity, component IComponent) error {
Logger.Trace().Str("component", c.GetName()).Msg("RemoveDelegateToRegister")
index := -1
for i, register := range c.registers {
if delegate != nil && delegate == register.GetDelegate() {
index = i
break
}
if entity == nil {
entity = c.GetEntity()
}
if _component := entity.GetComponent(component); _component != nil {
if _delegate := _component.GetDelegate(); _delegate != nil {
if _delegate == register.GetDelegate() {
index = i
break
}
}
}
}
if index != -1 {
GetDelegateManager().DeregisterFromDelegate(c.registers[index].GetRegisterID())
c.registers = append(c.registers[:index], c.registers[index+1:]...)
return nil
}
return fmt.Errorf("register not found for given input")
}
// SetActive sets component active attribute
func (c *Component) SetActive(active bool) {
c.active = active
}
// SetCache sets a new cache entry for the give key and data.
func (c *Component) SetCache(key string, data interface{}) {
c.cache[key] = data
}
// SetCustomOnUpdate sets the custom call to be executed OnUpdate.
func (c *Component) SetCustomOnUpdate(customCall func(IComponent)) {
c.customOnUpdate = customCall
}
// SetDelegate sets component delegate.
func (c *Component) SetDelegate(delegate IDelegate) {
c.delegate = delegate
}
// SetEntity sets component new entity instance.
func (c *Component) SetEntity(entity IEntity) {
c.entity = entity
}
// SetRemoveOnDestroy sets component remove on destroy. If this attribute
// is true, the component will be removed from the entity when scene is
// fully unloaded.
func (c *Component) SetRemoveOnDestroy(remove bool) {
c.removeOnDestroy = remove
}
// Unmarshal takes a ComponentToMarshal instance and creates a new entity
// instance.
func (c *Component) Unmarshal(data map[string]interface{}) {
c.SetName(data["name"].(string))
}