forked from xiaonanln/goworld
/
EntityManager.go
655 lines (550 loc) · 18.1 KB
/
EntityManager.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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
package entity
import (
"reflect"
"strings"
"github.com/pkg/errors"
"github.com/xiaonanln/goworld/engine/common"
"github.com/xiaonanln/goworld/engine/consts"
"github.com/xiaonanln/goworld/engine/dispatchercluster"
"github.com/xiaonanln/goworld/engine/gwlog"
"github.com/xiaonanln/goworld/engine/gwutils"
"github.com/xiaonanln/goworld/engine/storage"
"github.com/xiaonanln/typeconv"
)
var (
registeredEntityTypes = map[string]*EntityTypeDesc{}
entityManager = newEntityManager()
)
// EntityTypeDesc is the entity type description for registering entity types
type EntityTypeDesc struct {
isService bool
IsPersistent bool
useAOI bool
entityType reflect.Type
rpcDescs rpcDescMap
allClientAttrs common.StringSet
clientAttrs common.StringSet
persistentAttrs common.StringSet
//compositiveMethodComponentIndices map[string][]int
//definedAttrs bool
}
var _VALID_ATTR_DEFS = common.StringSet{} // all valid attribute defs
func init() {
_VALID_ATTR_DEFS.Add(strings.ToLower("Client"))
_VALID_ATTR_DEFS.Add(strings.ToLower("AllClients"))
_VALID_ATTR_DEFS.Add(strings.ToLower("Persistent"))
}
func (desc *EntityTypeDesc) SetPersistent(persistent bool) *EntityTypeDesc {
desc.IsPersistent = persistent
return desc
}
func (desc *EntityTypeDesc) SetUseAOI(useAOI bool) *EntityTypeDesc {
desc.useAOI = useAOI
return desc
}
func (desc *EntityTypeDesc) DefineAttr(attr string, defs ...string) *EntityTypeDesc {
gwlog.Infof(" Attr %s = %v", attr, defs)
isAllClient, isClient, isPersistent := false, false, false
for _, def := range defs {
def := strings.ToLower(def)
if !_VALID_ATTR_DEFS.Contains(def) {
// not a valid def
gwlog.Panicf("attribute %s: invalid property: %s; all valid properties: %v", attr, def, _VALID_ATTR_DEFS.ToList())
}
if def == "allclients" {
isAllClient = true
isClient = true
} else if def == "client" {
isClient = true
} else if def == "persistent" {
isPersistent = true
// make sure non-persistent entity has no persistent attributes
if !desc.IsPersistent {
gwlog.Fatalf("Entity type %s is not persistent, should not define persistent attribute: %s", desc.entityType.Name(), attr)
}
}
}
if isAllClient {
desc.allClientAttrs.Add(attr)
}
if isClient {
desc.clientAttrs.Add(attr)
}
if isPersistent {
desc.persistentAttrs.Add(attr)
}
return desc
}
type _EntityManager struct {
entities EntityMap
entitiesByType map[string]EntityMap
}
func newEntityManager() *_EntityManager {
return &_EntityManager{
entities: EntityMap{},
entitiesByType: map[string]EntityMap{},
}
}
func (em *_EntityManager) put(entity *Entity) {
em.entities.Add(entity)
etype := entity.TypeName
eid := entity.ID
if entities, ok := em.entitiesByType[etype]; ok {
entities.Add(entity)
} else {
em.entitiesByType[etype] = EntityMap{eid: entity}
}
}
func (em *_EntityManager) del(e *Entity) {
eid := e.ID
em.entities.Del(eid)
if entities, ok := em.entitiesByType[e.TypeName]; ok {
entities.Del(eid)
}
}
func (em *_EntityManager) get(id common.EntityID) *Entity {
return em.entities.Get(id)
}
func (em *_EntityManager) traverseByType(etype string, cb func(e *Entity)) {
entities := em.entitiesByType[etype]
for _, e := range entities {
cb(e)
}
}
func (em *_EntityManager) onGateDisconnected(gateid uint16) {
for _, entity := range em.entities {
client := entity.client
if client != nil && client.gateid == gateid {
entity.notifyClientDisconnected()
}
}
}
// RegisterEntity registers custom entity type and define entity behaviors
func RegisterEntity(typeName string, entity IEntity, isService bool) *EntityTypeDesc {
if _, ok := registeredEntityTypes[typeName]; ok {
gwlog.Fatalf("RegisterEntity: Entity type %s already registered", typeName)
}
entityVal := reflect.ValueOf(entity)
entityType := entityVal.Type()
if entityType.Kind() == reflect.Ptr {
entityType = entityType.Elem()
}
// register the string of e
rpcDescs := rpcDescMap{}
entityTypeDesc := &EntityTypeDesc{
isService: isService,
IsPersistent: false,
useAOI: false,
entityType: entityType,
rpcDescs: rpcDescs,
clientAttrs: common.StringSet{},
allClientAttrs: common.StringSet{},
persistentAttrs: common.StringSet{},
//compositiveMethodComponentIndices: map[string][]int{},
}
registeredEntityTypes[typeName] = entityTypeDesc
entityPtrType := reflect.PtrTo(entityType)
numMethods := entityPtrType.NumMethod()
for i := 0; i < numMethods; i++ {
method := entityPtrType.Method(i)
rpcDescs.visit(method)
}
gwlog.Infof(">>> RegisterEntity %s => %s <<<", typeName, entityType.Name())
//// define entity Attrs
entity.DescribeEntityType(entityTypeDesc)
return entityTypeDesc
//e.callCompositiveMethod("DescribeEntityType", entityTypeDesc)
}
func GetEntityTypeDesc(typeName string) *EntityTypeDesc {
return registeredEntityTypes[typeName]
}
var entityType = reflect.TypeOf(Entity{})
func isEntityType(t reflect.Type) bool {
if t == entityType {
return true
}
if t.Kind() != reflect.Struct {
return false
}
entityField, ok := t.FieldByName("Entity")
return ok && entityField.Type == entityType
}
//var componentType = reflect.TypeOf(Component{})
//func isComponentType(t reflect.Type) bool {
// //if t == componentType {
// // return true
// //}
// if t.Kind() != reflect.Struct {
// return false
// }
// componentField, ok := t.FieldByName("Component")
// return ok && componentField.Type == componentType
//}
//type createCause int
//
//const (
// ccCreate createCause = 1 + iota
// ccMigrate
// ccRestore
//)
func createEntity(typeName string, space *Space, pos Vector3, entityID common.EntityID, data map[string]interface{}) *Entity {
//gwlog.Debugf("createEntity: %s in Space %s", typeName, space)
entityTypeDesc, ok := registeredEntityTypes[typeName]
if !ok {
gwlog.Panicf("unknown entity type: %s", typeName)
}
if entityID == "" {
entityID = common.GenEntityID()
}
var entity *Entity
var entityInstance reflect.Value
entityInstance = reflect.New(entityTypeDesc.entityType)
entity = reflect.Indirect(entityInstance).FieldByName("Entity").Addr().Interface().(*Entity)
entity.init(typeName, entityID, entityInstance)
entity.Space = nilSpace
entityManager.put(entity)
if data != nil {
entity.loadPersistentData(data)
} else {
entity.Save() // save immediately after creation
}
isPersistent := entity.IsPersistent()
if isPersistent { // startup the periodical timer for saving e
entity.setupSaveTimer()
}
dispatchercluster.SendNotifyCreateEntity(entityID)
gwlog.Debugf("Entity %s created.", entity)
gwutils.RunPanicless(func() {
entity.I.OnAttrsReady()
entity.I.OnCreated()
})
if space != nil {
space.enter(entity, pos, false)
}
return entity
}
func restoreEntity(entityID common.EntityID, mdata *entityMigrateData, isRestore bool) {
//gwlog.Debugf("restoring entity %s: mdata=%+v, isRestore=%v", entityID, mdata, isRestore)
typeName := mdata.Type
entityTypeDesc, ok := registeredEntityTypes[typeName]
if !ok {
gwlog.Panicf("unknown entity type: %s", typeName)
}
var entity *Entity
var entityInstance reflect.Value
entityInstance = reflect.New(entityTypeDesc.entityType)
entity = reflect.Indirect(entityInstance).FieldByName("Entity").Addr().Interface().(*Entity)
entity.init(typeName, entityID, entityInstance)
entity.Space = nilSpace
entity.Position = mdata.Pos
entity.yaw = mdata.Yaw
entityManager.put(entity)
entity.loadMigrateData(mdata.Attrs)
timerData := mdata.TimerData
if timerData != nil {
entity.restoreTimers(timerData)
}
isPersistent := entity.IsPersistent()
if isPersistent { // startup the periodical timer for saving e
entity.setupSaveTimer()
}
entity.syncInfoFlag = mdata.SyncInfoFlag
entity.syncingFromClient = mdata.SyncingFromClient
if mdata.Client != nil {
client := MakeGameClient(mdata.Client.ClientID, mdata.Client.GateID)
// assign Client to the newly created
entity.assignClient(client) // assign Client quietly
}
gwlog.Debugf("Entity %s created, Client=%s", entity, entity.client)
gwutils.RunPanicless(func() {
entity.I.OnAttrsReady()
})
if !isRestore {
gwutils.RunPanicless(func() {
entity.I.OnMigrateIn()
})
}
space := spaceManager.getSpace(mdata.SpaceID)
if space != nil {
space.enter(entity, mdata.Pos, isRestore)
}
if isRestore {
gwutils.RunPanicless(func() {
entity.I.OnRestored()
})
}
}
func loadEntityLocally(typeName string, entityID common.EntityID, space *Space, pos Vector3) {
// load the data from storage
storage.Load(typeName, entityID, func(_data interface{}, err error) {
// callback runs in main routine
if err != nil {
dispatchercluster.SendNotifyDestroyEntity(entityID) // load entity failed, tell dispatcher
gwlog.Panicf("load entity %s.%s failed: %s", typeName, entityID, err)
}
ex := entityManager.get(entityID) // existing entity
if ex != nil {
// should not happen because dispatcher won't allow, but just in case
gwlog.Panicf("load entity %s.%s failed: %s already exists", typeName, entityID, ex)
}
if space != nil && space.IsDestroyed() {
// Space might be destroy during the Load process, so cancel the entity creation
space = nil // if space is destroyed before creation, just use nil space
}
data := _data.(map[string]interface{})
// need to remove NOT persistent fields from data
entityTypeDesc := registeredEntityTypes[typeName]
removeFields := []string{}
for k, _ := range data {
if !entityTypeDesc.persistentAttrs.Contains(k) {
removeFields = append(removeFields, k)
}
}
for _, f := range removeFields {
delete(data, f)
}
createEntity(typeName, space, pos, entityID, data)
})
}
func createEntitySomewhere(gameid uint16, typeName string, data map[string]interface{}) common.EntityID {
entityid := common.GenEntityID()
dispatchercluster.SendCreateEntitySomewhere(gameid, entityid, typeName, data)
return entityid
}
// CreateEntityLocally creates new entity in the local game
func CreateEntityLocally(typeName string, data map[string]interface{}) *Entity {
return createEntity(typeName, nil, Vector3{}, "", data)
}
// CreateEntityLocallyWithEntityID creates new entity in the local game with specified entity ID
func CreateEntityLocallyWithID(typeName string, data map[string]interface{}, id common.EntityID) *Entity {
return createEntity(typeName, nil, Vector3{}, id, data)
}
// CreateEntitySomewhere creates new entity in any game
func CreateEntitySomewhere(gameid uint16, typeName string) common.EntityID {
return createEntitySomewhere(gameid, typeName, nil)
}
// OnCreateEntitySomewhere is called when CreateEntitySomewhere chooses this game
func OnCreateEntitySomewhere(entityid common.EntityID, typeName string, data map[string]interface{}) {
createEntity(typeName, nil, Vector3{}, entityid, data)
}
// OnLoadEntitySomewhere loads entity in the local game.
func OnLoadEntitySomewhere(typeName string, entityID common.EntityID) {
loadEntityLocally(typeName, entityID, nil, Vector3{})
}
// LoadEntityAnywhere loads entity in the any game
//
// LoadEntityAnywhere has no effect if entity already exists on any game
func LoadEntityAnywhere(typeName string, entityID common.EntityID) {
dispatchercluster.SendLoadEntityAnywhere(typeName, entityID)
}
func LoadEntityOnGame(typeName string, entityID common.EntityID, gameid uint16) {
dispatchercluster.SendLoadEntityOnGame(typeName, entityID, gameid)
}
// OnClientDisconnected is called by engine when Client is disconnected
func OnClientDisconnected(ownerID common.EntityID, clientid common.ClientID) {
owner := entityManager.get(ownerID)
if owner != nil {
if owner.client != nil && owner.client.clientid == clientid {
owner.notifyClientDisconnected()
} else {
gwlog.Warnf("client %s is disconnected, but owner entity %s has client %s", clientid, owner, owner.client)
}
} else {
gwlog.Warnf("owner entity %s not found for client %s, might already be destroyed", ownerID, clientid)
}
}
func Call(id common.EntityID, method string, args []interface{}) {
if consts.OPTIMIZE_LOCAL_ENTITY_CALL {
e := entityManager.get(id)
if e != nil { // this entity is local, just call entity directly
e.Post(func() {
e.onCallFromLocal(method, args)
})
} else {
callRemote(id, method, args)
}
} else {
callRemote(id, method, args)
}
}
func CallNilSpaces(method string, args []interface{}, gameid uint16) {
if consts.OPTIMIZE_LOCAL_ENTITY_CALL {
dispatchercluster.SendCallNilSpaces(gameid, method, args)
nilSpace.onCallFromLocal(method, args)
} else {
dispatchercluster.SendCallNilSpaces(0, method, args)
}
}
func OnCallNilSpaces(method string, args [][]byte) {
nilSpace.onCallFromRemote(method, args, "")
}
func callRemote(id common.EntityID, method string, args []interface{}) {
dispatchercluster.SelectByEntityID(id).SendCallEntityMethod(id, method, args)
}
var lastWarnedOnCallMethod = ""
// OnCall is called by engine when method call reaches in the game
func OnCall(id common.EntityID, method string, args [][]byte, clientID common.ClientID) {
e := entityManager.get(id)
if e == nil {
// entity not found, may destroyed before call
if method != lastWarnedOnCallMethod {
gwlog.Warnf("OnCall: entity %s is not found while calling %s", id, method)
lastWarnedOnCallMethod = method
}
return
}
e.onCallFromRemote(method, args, clientID)
}
// OnSyncPositionYawFromClient is called by engine to sync entity infos from Client
func OnSyncPositionYawFromClient(eid common.EntityID, x, y, z Coord, yaw Yaw) {
e := entityManager.get(eid)
if e == nil {
// entity not found, may destroyed before call
//gwlog.Errorf("OnSyncPositionYawFromClient: entity %s is not found", eid)
return
}
e.syncPositionYawFromClient(x, y, z, yaw)
}
// GetEntity returns the entity with specified ID
func GetEntity(id common.EntityID) *Entity {
return entityManager.get(id)
}
func GetEntitiesByType(etype string) EntityMap {
return entityManager.entitiesByType[etype]
}
// TraverseEntityByType traverses entities of the specified type
func TraverseEntityByType(etype string, cb func(e *Entity)) {
entityManager.traverseByType(etype, cb)
}
// OnGameTerminating is called when game is terminating
func OnGameTerminating() {
for _, e := range entityManager.entities {
e.Destroy()
}
}
var allGamesConnected bool
// OnAllGamesConnected is called when all games are connected to dispatcher cluster
func OnAllGamesConnected() {
if allGamesConnected {
gwlog.Warnf("all games connected, but not for the first time")
//gwlog.Warnf("registered services: %+v", entityManager.registeredServices)
return
}
allGamesConnected = true
gwlog.Infof("all games connected, nil space = %s", nilSpace)
if nilSpace != nil {
nilSpace.I.OnGameReady()
}
}
// OnGateDisconnected is called when gate is down
func OnGateDisconnected(gateid uint16) {
gwlog.Warnf("Gate %d disconnected", gateid)
entityManager.onGateDisconnected(gateid)
}
// SaveAllEntities saves all entities
func SaveAllEntities() {
for _, e := range entityManager.entities {
e.Save()
}
}
// Called by engine when server is freezing
// FreezeData is the data structure for storing entity freeze data
type FreezeData struct {
Entities map[common.EntityID]*entityMigrateData
}
// Freeze freezes the entity system and returns all freeze data
func Freeze(gameid uint16) (*FreezeData, error) {
freeze := FreezeData{}
entityFreezeInfos := map[common.EntityID]*entityMigrateData{}
foundNilSpace := false
for _, e := range entityManager.entities {
err := gwutils.CatchPanic(func() {
e.I.OnFreeze()
//e.callCompositiveMethod("OnFreeze")
})
if err != nil {
// OnFreeze failed
return nil, errors.Errorf("OnFreeze paniced: %v", err)
}
entityFreezeInfos[e.ID] = e.getFreezeData()
if e.IsSpaceEntity() {
if e.AsSpace().IsNil() {
if foundNilSpace {
return nil, errors.Errorf("found duplicate nil space")
}
foundNilSpace = true
}
}
}
if !foundNilSpace { // there should be exactly one nil space!
return nil, errors.Errorf("nil space not found")
}
freeze.Entities = entityFreezeInfos
//registeredServices := make(map[string][]common.EntityID, len(entityManager.registeredServices))
//for serviceName, eids := range entityManager.registeredServices {
// registeredServices[serviceName] = eids.ToList()
//}
//freeze.Services = registeredServices
return &freeze, nil
}
// RestoreFreezedEntities restore entity system from freeze data
func RestoreFreezedEntities(freeze *FreezeData) (err error) {
defer func() {
_err := recover()
if _err != nil {
err = errors.Wrap(_err.(error), "panic during restore")
}
}()
clients := map[common.EntityID]*GameClient{} // save all the clients when restoring entities
restoreEntities := func(filter func(typeName string, spaceKind int64) bool) {
for eid, info := range freeze.Entities {
typeName := info.Type
var spaceKind int64
if typeName == _SPACE_ENTITY_TYPE {
spaceKind = typeconv.Int(info.Attrs[_SPACE_KIND_ATTR_KEY])
}
if filter(typeName, spaceKind) {
var space *Space
if typeName != _SPACE_ENTITY_TYPE {
space = spaceManager.getSpace(info.SpaceID)
}
var client *GameClient
if info.Client != nil {
client = MakeGameClient(info.Client.ClientID, info.Client.GateID)
clients[eid] = client // save the Client to the map
info.Client = nil
}
restoreEntity(eid, info, true)
gwlog.Debugf("Restored %s<%s> in space %s", typeName, eid, space)
}
}
}
// step 1: restore the nil space
restoreEntities(func(typeName string, spaceKind int64) bool {
return typeName == _SPACE_ENTITY_TYPE && spaceKind == 0
})
// step 2: restore all other spaces
restoreEntities(func(typeName string, spaceKind int64) bool {
return typeName == _SPACE_ENTITY_TYPE && spaceKind != 0
})
// step 3: restore all other spaces
restoreEntities(func(typeName string, spaceKind int64) bool {
return typeName != _SPACE_ENTITY_TYPE
})
// restore clients to all entities
for eid, client := range clients {
e := entityManager.get(eid)
if e != nil {
e.assignClient(client) // assign Client quietly if migrate
} else {
gwlog.Errorf("entity %s restore failed? can not set Client %s", eid, client)
}
}
return nil
}
// Entities gets all entities
//
// Never modify the return value !
func Entities() EntityMap {
return entityManager.entities
}