-
Notifications
You must be signed in to change notification settings - Fork 0
/
blueprint.go
323 lines (289 loc) · 8.58 KB
/
blueprint.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
package main
import (
"context"
"errors"
"fmt"
"os"
"strings"
"sync"
)
var LoaderNotFoundError = errors.New("loader not found")
var ParseError = errors.New("invalid json value")
var PrototypeError = errors.New("unable to copy from prototype")
var InstanceError = errors.New("unable to instance object")
var NoInfo = BlueprintInfo{}
type loadError struct {
path string
err error
}
func (receiver loadError) Error() string {
return fmt.Sprintf("\"%s\" at path %s", receiver.err, receiver.path)
}
func (receiver loadError) Unwrap() error {
return receiver.err
}
type LoadErrors struct {
e []error
t []string //trace
}
func (receiver *LoadErrors) HasError() bool {
if len(receiver.e) > 0 {
return true
} else {
return false
}
}
func (receiver *LoadErrors) Error() string {
var s []string
for _, err := range receiver.e {
s = append(s, err.Error()) // Конвертирует ошибки в строки
}
return strings.Join(s, ", ")
}
// add and check error non null
func (receiver *LoadErrors) Add(error error) bool {
if error != nil {
var sl []string
if len(receiver.t) > 1 {
sl = receiver.t[1:] //without root
} else {
sl = receiver.t[:]
}
le := &loadError{
path: "/" + strings.Join(sl, "/"),
err: error,
}
receiver.e = append(receiver.e, le)
return true
}
return false
}
func (receiver *LoadErrors) tracePush(p string) {
receiver.t = append(receiver.t, p)
}
func (receiver *LoadErrors) tracePop() string {
v := receiver.t[len(receiver.t)-1]
receiver.t = receiver.t[0 : len(receiver.t)-1]
return v
}
func newLoadErrors() (*LoadErrors, error) {
instance := new(LoadErrors)
instance.e = make([]error, 0)
instance.t = make([]string, 0)
return instance, nil
}
type LoaderGetter func(blueprint string) Loader
type Loader func(ctx context.Context, get LoaderGetter, eCollector *LoadErrors, preset interface{}, payload []byte) interface{}
type Builder func() interface{}
type RequireFunc func(blueprint string) error
type InfoFunc func(blueprint string) (BlueprintInfo, error)
type FileBuf struct {
buf []byte
err error
}
type BlueprintInfo struct {
Attributes
*Tags
}
type BlueprintManager struct {
EventChanel EventChanel
GameConfig *GameConfig
FilePool map[string]*FileBuf
FilePath string
FileExtension string
loaders map[string]Loader
proto map[string]ObjectInterface
protoShadow map[string]ObjectInterface
m sync.Mutex
}
func (receiver *BlueprintManager) Get(blueprint string) (ObjectInterface, error) {
if object, ok := receiver.proto[blueprint]; ok {
return receiver.copy(object)
}
receiver.m.Lock()
defer receiver.m.Unlock() //concurent sprite and collector problem
return receiver.get(blueprint)
}
func (receiver *BlueprintManager) Info(blueprint string) (BlueprintInfo, error) {
if object, ok := receiver.proto[blueprint]; ok {
tags, err := GetTags(object)
if err != nil {
return NoInfo, err
} else {
return BlueprintInfo{
Attributes: *object.GetAttr(),
Tags: tags.Copy(),
}, nil
}
}
return NoInfo, PrototypeError
}
func (receiver *BlueprintManager) CreateBuilder(blueprint string) (Builder, error) {
object, err := receiver.Get(blueprint)
if object == nil { //may be error even on success
if err != nil {
logger.Println(err.Error())
}
return nil, err
}
if err != nil {
logger.Println(err.Error()) //try to ignore spam of errors, logs only first
}
return func() interface{} {
obj, _ := receiver.Get(blueprint) //todo do some, log errors
return obj
}, nil
}
func (receiver *BlueprintManager) AddLoader(blueprint string, loader Loader) {
receiver.loaders[blueprint] = receiver.wrapLoader(loader, blueprint)
}
func (receiver *BlueprintManager) AddLoaderPackage(p *Package) {
for blueprint, loader := range p.M {
receiver.loaders[blueprint] = receiver.wrapLoader(loader, blueprint)
}
receiver.FilePath = p.FilePath
receiver.FileExtension = p.FileExtension
}
func (receiver *BlueprintManager) get(blueprint string) (ObjectInterface, error) {
if object, ok := receiver.proto[blueprint]; ok {
return receiver.copy(object) //try again
}
payload, _ := receiver.load(blueprint)
if root, ok := receiver.loaders["/"]; ok {
collector, _ := newLoadErrors()
if stuff := root(context.TODO(), receiver.getLoader, collector, nil, payload); stuff == nil {
collector.Add(errors.New("object wont created"))
return nil, collector
} else {
if object, ok := stuff.(ObjectInterface); ok {
object.GetAttr().Blueprint = blueprint
object = receiver.postProcess(object, collector)
receiver.protoShadow[blueprint] = object
receiver.proto, receiver.protoShadow = receiver.protoShadow, receiver.proto
if _, ok := receiver.protoShadow[blueprint]; ok {
panic("shadow copy violation")
} else {
receiver.protoShadow[blueprint] = object
}
object, err := receiver.copy(object)
collector.Add(err)
if !collector.HasError() {
return object, nil
} else {
return object, collector
}
} else {
return nil, collector
}
}
}
return nil, LoaderNotFoundError
}
func (receiver *BlueprintManager) wrapLoader(loader Loader, blueprint string) Loader {
return func(ctx context.Context, get LoaderGetter, eCollector *LoadErrors, preset interface{}, payload []byte) interface{} {
eCollector.tracePush(blueprint) //trace wrapper
ret := loader(ctx, get, eCollector, preset, payload)
eCollector.tracePop()
return ret
}
}
func (receiver *BlueprintManager) postProcess(object ObjectInterface, collector *LoadErrors) ObjectInterface {
if object == nil {
return nil
}
if object.GetAttr().Motioner { //todo simplify //todo move to render
proxy := object.(Motioner)
scale := 2.0
proxy.GetSpeed().Y = proxy.GetSpeed().X / scale
acl := object.(Accelerator)
acl.GetMaxSpeed().Y = acl.GetMaxSpeed().X / scale
acl.GetMinSpeed().Y = acl.GetMinSpeed().X / scale
}
return object
}
func (receiver *BlueprintManager) load(id string) ([]byte, error) {
if content, ok := receiver.FilePool[id]; !ok {
buf, err := os.ReadFile(receiver.FilePath + "/" + id + "." + receiver.FileExtension)
receiver.FilePool[id] = &FileBuf{
buf: buf,
err: err,
}
return receiver.FilePool[id].buf, receiver.FilePool[id].err
} else {
return content.buf, content.err
}
}
func (receiver *BlueprintManager) getLoader(blueprint string) Loader {
return receiver.loaders[blueprint]
}
func (receiver *BlueprintManager) copy(object ObjectInterface) (ObjectInterface, error) {
switch object.(type) {
case *Unit:
unit := object.(*Unit).Copy()
unit.Prototype = object
unit.GetAttr().ID = genId()
return unit, nil
case *Wall:
wall := object.(*Wall).Copy()
wall.Prototype = object
wall.GetAttr().ID = genId()
return wall, nil
case *Projectile:
projectile := object.(*Projectile).Copy()
projectile.Prototype = object
projectile.GetAttr().ID = genId()
return projectile, nil
case *Explosion:
explosion := object.(*Explosion).Copy()
explosion.Prototype = object
explosion.GetAttr().ID = genId()
return explosion, nil
case *Collectable:
collectable := object.(*Collectable).Copy()
collectable.Prototype = object
collectable.GetAttr().ID = genId()
return collectable, nil
case *Object:
object2 := object.(*Object).Copy()
object2.Prototype = object
object2.GetAttr().ID = genId()
return object2, nil
case *MotionObject:
mo := object.(*MotionObject).Copy()
mo.Prototype = object
mo.GetAttr().ID = genId()
return mo, nil
case *SpawnPoint:
sp := object.(*SpawnPoint).Copy()
sp.Prototype = object
sp.GetAttr().ID = genId()
return sp, nil
default:
logger.Printf("blueprint copy, unknown object type %t", object)
}
return nil, PrototypeError
}
func NewBlueprintManager() (*BlueprintManager, error) {
instance := new(BlueprintManager)
instance.FilePool = make(map[string]*FileBuf)
instance.loaders = make(map[string]Loader)
instance.proto = make(map[string]ObjectInterface)
instance.protoShadow = make(map[string]ObjectInterface)
instance.AddLoader("eventChanel", func(ctx context.Context, get LoaderGetter, eCollector *LoadErrors, preset interface{}, payload []byte) interface{} {
return instance.EventChanel
})
instance.AddLoader("gameConfig", func(ctx context.Context, get LoaderGetter, eCollector *LoadErrors, preset interface{}, payload []byte) interface{} {
return instance.GameConfig
})
instance.AddLoader("require", func(ctx context.Context, get LoaderGetter, eCollector *LoadErrors, preset interface{}, payload []byte) interface{} {
return RequireFunc(func(blueprint string) error {
obj, err := instance.get(blueprint)
if obj != nil {
//todo fix this
return nil
}
return err
})
})
return instance, nil
}