-
Notifications
You must be signed in to change notification settings - Fork 23
/
PrefabJsonFormat.java
330 lines (294 loc) · 14.6 KB
/
PrefabJsonFormat.java
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
/*
* Copyright 2019 MovingBlocks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terasology.gestalt.entitysystem.prefab;
import com.google.common.collect.Queues;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.stream.JsonReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terasology.gestalt.assets.ResourceUrn;
import org.terasology.gestalt.assets.format.AbstractAssetFileFormat;
import org.terasology.gestalt.assets.format.AssetDataFile;
import org.terasology.gestalt.assets.management.AssetManager;
import org.terasology.gestalt.assets.management.Context;
import org.terasology.gestalt.assets.management.ContextManager;
import org.terasology.gestalt.entitysystem.component.Component;
import org.terasology.gestalt.entitysystem.component.management.ComponentManager;
import org.terasology.gestalt.entitysystem.component.management.ComponentType;
import org.terasology.gestalt.entitysystem.component.management.ComponentTypeIndex;
import org.terasology.gestalt.entitysystem.component.management.PropertyAccessor;
import org.terasology.gestalt.entitysystem.entity.EntityRef;
import org.terasology.gestalt.entitysystem.entity.NullEntityRef;
import org.terasology.gestalt.module.ModuleEnvironment;
import org.terasology.gestalt.naming.Name;
import org.terasology.gestalt.util.collection.TypeKeyedMap;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* An {@link org.terasology.gestalt.assets.format.AssetFileFormat} for loading prefab assets from json files.
*/
public class PrefabJsonFormat extends AbstractAssetFileFormat<PrefabData> {
public static final String DEFAULT_ROOT_ENTITY_NAME = "root";
private static final Logger logger = LoggerFactory.getLogger(PrefabJsonFormat.class);
private static final Name THIS = new Name("this");
private final ComponentTypeIndex componentIndex;
private final ComponentManager componentManager;
private final AssetManager assetManager;
private final Gson gson;
private final ThreadLocal<Deque<PrefabLoader>> loaderStack = new ThreadLocal<Deque<PrefabLoader>>() {
@Override
protected Deque<PrefabLoader> initialValue() {
return Queues.newArrayDeque();
}
};
public PrefabJsonFormat(ComponentTypeIndex componentIndex, ComponentManager componentManager, AssetManager assetManager, GsonBuilder gsonBuilder) {
super("json", "prefab");
this.componentIndex = componentIndex;
this.componentManager = componentManager;
this.assetManager = assetManager;
gsonBuilder.registerTypeAdapter(EntityRef.class, new EntityRefTypeHandler());
this.gson = gsonBuilder.create();
}
@Override
public PrefabData load(ResourceUrn urn, List<AssetDataFile> inputs) throws IOException {
try (Context ignored = ContextManager.beginContext(urn.getModuleName())) {
try (JsonReader reader = new JsonReader(new BufferedReader(new InputStreamReader(inputs.get(0).openStream())))) {
reader.setLenient(true);
JsonParser parser = new JsonParser();
JsonElement assetRoot = parser.parse(reader);
PrefabLoader loader = new PrefabLoader();
loaderStack.get().push(loader);
try {
return loader.load(assetRoot.getAsJsonObject(), urn);
} finally {
loaderStack.get().pop();
if (loaderStack.get().isEmpty()) {
loaderStack.remove();
}
}
}
}
}
/**
* A builder used to aid construction of {@link PrefabJsonFormat}
*/
public static class Builder {
private final ComponentTypeIndex componentTypeIndex;
private final ComponentManager componentManager;
private AssetManager assetManager;
private GsonBuilder gsonBuilder;
/**
* @param componentTypeIndex The component type index, used to discover available component types
* @param componentManager The manager for components, used to construct and work with components
* @param assetManager The asset manager, used to look up prefabs.
*/
public Builder(ComponentTypeIndex componentTypeIndex, ComponentManager componentManager, AssetManager assetManager) {
this.componentTypeIndex = componentTypeIndex;
this.componentManager = componentManager;
this.assetManager = assetManager;
gsonBuilder = new GsonBuilder()
.setLenient()
.enableComplexMapKeySerialization()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
}
/**
* Register a GSON type adapter. All the rules for {@link GsonBuilder}.registerTypeAdapter apply.
*
* @param type The type the adapter is for
* @param typeAdapter The adapter
* @return The builder.
*/
public Builder registerTypeAdapter(Type type, Object typeAdapter) {
gsonBuilder.registerTypeAdapter(type, typeAdapter);
return this;
}
/**
* Register a GSON type hierarchy adapter. All the rules for {@link GsonBuilder}.registerTypeHierarchyAdapter apply.
*
* @param type The type the adapter is for
* @param typeAdapter The adapter
* @return The builder
*/
public Builder registerTypeHierarchyAdapter(Class<?> type, Object typeAdapter) {
gsonBuilder.registerTypeHierarchyAdapter(type, typeAdapter);
return this;
}
/**
* Register a GSON type adapter factory. All the rules for {@link GsonBuilder}.registerTypeAdapterFactory apply.
*
* @param factory The type adapter factory to register
* @return The builder
*/
public Builder registerTypeAdapterFactory(TypeAdapterFactory factory) {
gsonBuilder.registerTypeAdapterFactory(factory);
return this;
}
/**
* @return The new PrefabJsonFormat.
*/
public PrefabJsonFormat create() {
return new PrefabJsonFormat(componentTypeIndex, componentManager, assetManager, gsonBuilder);
}
}
private class EntityRefTypeHandler implements JsonDeserializer<EntityRef> {
@Override
public EntityRef deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
String refString = json.getAsJsonPrimitive().getAsString();
if (ResourceUrn.isValid(refString)) {
return readUrnRef(refString);
} else {
return readSimpleRef(refString);
}
}
private EntityRef readSimpleRef(String refString) {
PrefabLoader loader = loaderStack.get().peek();
EntityRef ref = null;
EntityRecipe recipe = loader.prefabData.getRecipes().get(new ResourceUrn(loader.prefabUrn, refString));
if (recipe != null) {
ref = recipe.getReference();
} else {
Optional<Prefab> refPrefab = assetManager.getAsset(refString, Prefab.class);
if (refPrefab.isPresent()) {
ref = new PrefabRef(refPrefab.get());
}
}
if (ref == null) {
logger.error("Unable to resolve entity or prefab reference {}", refString);
return NullEntityRef.get();
}
return ref;
}
private EntityRef readUrnRef(String refString) {
ResourceUrn refUrn = new ResourceUrn(refString);
if (THIS.equals(refUrn.getModuleName())) {
return readEntityRecipeRef(refUrn.getResourceName().toString());
}
Optional<Prefab> refPrefab = assetManager.getAsset(refString, Prefab.class);
if (refPrefab.isPresent()) {
return new PrefabRef(refPrefab.get());
} else {
logger.error("Unable to resolve prefab reference {}", refString);
return NullEntityRef.get();
}
}
private EntityRef readEntityRecipeRef(String refString) {
PrefabLoader loader = loaderStack.get().peek();
EntityRecipe recipe = loader.prefabData.getRecipes().get(new ResourceUrn(loader.prefabUrn, refString));
if (recipe == null) {
logger.error("Unable to resolve entity reference {}", refString);
return NullEntityRef.get();
} else {
return recipe.getReference();
}
}
}
private class PrefabLoader {
public static final String INHERIT = "inherit";
public static final String ENTITIES = "entities";
public static final String ENTITY = "entity";
public static final String ROOT = "root";
private PrefabData prefabData;
private ResourceUrn prefabUrn;
public PrefabData load(JsonObject prefabDataObject, ResourceUrn prefabUrn) throws IOException {
this.prefabUrn = prefabUrn;
this.prefabData = new PrefabData();
if (prefabDataObject.has(INHERIT)) {
inheritPrefab(prefabDataObject.getAsJsonPrimitive(INHERIT).getAsString());
}
if (prefabDataObject.has(ENTITIES)) {
loadEntitiesFromJson(prefabUrn, prefabDataObject.getAsJsonObject(ENTITIES));
} else if (prefabDataObject.has(ENTITY)) {
loadEntityFromJson(prefabUrn, prefabDataObject.getAsJsonObject(ENTITY));
} else {
throw new IOException("Prefab file missing entity definition");
}
if (prefabDataObject.has(ROOT)) {
prefabData.setRootEntityId(new ResourceUrn(prefabUrn, prefabDataObject.getAsJsonPrimitive(ROOT).getAsString()));
} else if (prefabData.getRecipes().containsKey(new ResourceUrn(prefabUrn, DEFAULT_ROOT_ENTITY_NAME))) {
prefabData.setRootEntityId(new ResourceUrn(prefabUrn, DEFAULT_ROOT_ENTITY_NAME));
}
return prefabData;
}
private void loadEntitiesFromJson(ResourceUrn prefabUrn, JsonObject entities) throws IOException {
for (Map.Entry<String, JsonElement> entry : entities.entrySet()) {
addEntityRecipeIfMissing(new ResourceUrn(prefabUrn, entry.getKey()));
}
for (Map.Entry<String, JsonElement> entry : entities.entrySet()) {
ResourceUrn entityUrn = new ResourceUrn(prefabUrn, entry.getKey());
loadEntityRecipe(prefabData.getRecipes().get(entityUrn), entry.getValue().getAsJsonObject());
}
}
private void loadEntityFromJson(ResourceUrn prefabUrn, JsonObject entity) throws IOException {
ResourceUrn entityUrn = new ResourceUrn(prefabUrn, DEFAULT_ROOT_ENTITY_NAME);
addEntityRecipeIfMissing(entityUrn);
loadEntityRecipe(prefabData.getRecipes().get(entityUrn), entity);
}
private void addEntityRecipeIfMissing(ResourceUrn entityUrn) {
if (!prefabData.getRecipes().containsKey(entityUrn)) {
prefabData.addEntityRecipe(new EntityRecipe(entityUrn));
}
}
private void inheritPrefab(String parentPrefabUrn) throws IOException {
Prefab parentPrefab = assetManager.getAsset(parentPrefabUrn, Prefab.class).orElseThrow(() -> new IOException("Unable to resolve parent prefab " + parentPrefabUrn + " for prefab " + prefabUrn));
for (EntityRecipe recipe : parentPrefab.getEntityRecipes().values()) {
EntityRecipe copy = new EntityRecipe(new ResourceUrn(prefabUrn, recipe.getIdentifier().getFragmentName()));
recipe.getComponents().forEach(new TypeKeyedMap.EntryConsumer<Component>() {
@Override
@SuppressWarnings("unchecked")
public <U extends Component> void accept(Class<U> type, U value) {
copy.add(componentManager.copy(value));
}
});
prefabData.addEntityRecipe(copy);
}
}
private void loadEntityRecipe(EntityRecipe entityRecipe, JsonObject entityPrefabData) throws IOException {
for (Map.Entry<String, JsonElement> componentData : entityPrefabData.entrySet()) {
Class<? extends Component> componentClass = componentIndex.find(componentData.getKey()).orElseThrow(() -> new IOException("Unable to resolve component '" + componentData.getKey() + "'"));
loadComponent(entityRecipe, componentClass, componentData.getValue().getAsJsonObject());
}
}
private <T extends Component<T>> void loadComponent(EntityRecipe entityRecipe, Class<T> componentClass, JsonObject value) {
ComponentType<T> type = componentManager.getType(componentClass);
T component = entityRecipe.getComponent(componentClass).orElseGet(() -> {
T newComp = type.create();
entityRecipe.add(newComp);
return newComp;
});
type.getPropertyInfo().getProperties().entrySet().stream().filter(properties -> value.has(properties.getKey())).forEach(properties -> {
PropertyAccessor<T, ?> propertyAccessor = properties.getValue();
readProperty(properties.getKey(), value, component, propertyAccessor);
});
}
private <T extends Component, U> void readProperty(String name, JsonObject value, T component, PropertyAccessor<T, U> propertyAccessor) {
propertyAccessor.set(component, gson.fromJson(value.get(name), propertyAccessor.getPropertyType()));
}
}
}