-
Notifications
You must be signed in to change notification settings - Fork 0
/
keyvalues.go
94 lines (82 loc) · 2.21 KB
/
keyvalues.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
package vmt
import (
keyvalues "github.com/galaco/KeyValues"
"reflect"
"strings"
)
// FromKeyValues builds a material from keyvalue definitions.
// Please note that `include` keys cannot be automatically resolved
// using this method of parsing.
func FromKeyValues(kvs *keyvalues.KeyValue, definition Material) (Material, error) {
return unmarshalKeyvalues(kvs, definition)
}
func unmarshalKeyvalues(kvs *keyvalues.KeyValue, definition Material) (mat Material, err error) {
mat = definition
defer func() {
if r := recover(); r != nil {
if je, ok := r.(error); ok {
err = je
} else {
panic(r)
}
}
}()
defType := reflect.TypeOf(definition).Elem()
valueType := reflect.ValueOf(definition).Elem()
root := *kvs
fastMap, err := createKeyvalueFastMap(&root)
if err != nil {
return nil, err
}
fastMap["__SHADER_NAME__"] = keyvalues.NewKeyValuePair("__SHADER_NAME__", root.Key(), keyvalues.ValueString)
for i := 0; i < valueType.NumField(); i++ {
tag, ok := defType.Field(i).Tag.Lookup("vmt")
if !ok {
continue
}
if kv, ok := fastMap[strings.ToLower(tag)]; ok {
switch kv.Type() {
case keyvalues.ValueInt, keyvalues.ValueFloat:
{
switch valueType.Field(i).Interface().(type) {
case int:
if kv.Type() == keyvalues.ValueFloat {
val, _ := kv.AsInt()
valueType.Field(i).SetInt(int64(val))
continue
}
val, _ := kv.AsInt()
valueType.Field(i).SetInt(int64(val))
case float32, float64:
if kv.Type() == keyvalues.ValueInt {
val, _ := kv.AsFloat()
valueType.Field(i).SetFloat(float64(val))
continue
}
val, _ := kv.AsFloat()
valueType.Field(i).SetFloat(float64(val))
}
}
case keyvalues.ValueString:
val, _ := kv.AsString()
valueType.Field(i).SetString(val)
default:
}
}
}
return definition, nil
}
func createKeyvalueFastMap(kvs *keyvalues.KeyValue) (map[string]*keyvalues.KeyValue, error) {
if !kvs.HasChildren() {
return nil, ErrorMaterialKeyValuesEmpty
}
children, err := kvs.Children()
if err != nil {
return nil, err
}
fastmap := make(map[string]*keyvalues.KeyValue)
for _, c := range children {
fastmap[strings.ToLower(c.Key())] = c
}
return fastmap, nil
}