use of org.spongepowered.api.ResourceKey in project SpongeCommon by SpongePowered.
the class SpongeDataStoreBuilder method getDeserializer.
@SuppressWarnings({ "rawtypes", "unchecked" })
public <T> BiFunction<DataView, DataQuery, Optional<T>> getDeserializer(final Type elementType) {
final Class<?> rawType = GenericTypeReflector.erase(elementType);
if (DataView.class.isAssignableFrom(rawType)) {
return (view, dataQuery) -> (Optional<T>) view.getView(dataQuery);
}
if (DataSerializable.class.isAssignableFrom(rawType)) {
return (view, dataQuery) -> (Optional<T>) view.getSerializable(dataQuery, (Class<? extends DataSerializable>) rawType);
}
final Optional<RegistryType<Object>> registryTypeForValue = SpongeDataManager.INSTANCE.findRegistryTypeFor(rawType);
if (registryTypeForValue.isPresent()) {
return (view, dataQuery) -> (Optional<T>) registryTypeForValue.flatMap(regType -> view.getRegistryValue(dataQuery, regType));
}
if (ResourceKey.class.isAssignableFrom(rawType)) {
return (view, dataQuery) -> (Optional<T>) view.getString(dataQuery).map(ResourceKey::resolve);
}
if (Sponge.game().dataManager().translator(rawType).isPresent()) {
return (view, dataQuery) -> (Optional<T>) view.getObject(dataQuery, rawType);
}
if (Set.class.isAssignableFrom(rawType)) {
final Type listType = ((ParameterizedType) elementType).getActualTypeArguments()[0];
return (view, dataQuery) -> (Optional<T>) SpongeDataStoreBuilder.deserializeList((Class<?>) listType, view, dataQuery).map(list -> new HashSet(list));
}
if (List.class.isAssignableFrom(rawType)) {
final Type listType = ((ParameterizedType) elementType).getActualTypeArguments()[0];
return (view, dataQuery) -> (Optional<T>) SpongeDataStoreBuilder.deserializeList((Class<?>) listType, view, dataQuery);
}
if (Collection.class.isAssignableFrom(rawType)) {
throw new UnsupportedOperationException("Collection deserialization is not supported. Provide the deserializer for it.");
}
if (Types.isArray(elementType)) {
final Class arrayType = GenericTypeReflector.erase(GenericTypeReflector.getArrayComponentType(elementType));
return (view, dataQuery) -> (Optional<T>) SpongeDataStoreBuilder.deserializeList((Class<?>) arrayType, view, dataQuery).map(list -> this.listToArray(arrayType, list));
}
if (Map.class.isAssignableFrom(rawType)) {
final Type[] parameterTypes = ((ParameterizedType) elementType).getActualTypeArguments();
final Type keyType = parameterTypes[0];
final Type valueType = parameterTypes[1];
if (!(keyType instanceof Class)) {
throw new UnsupportedOperationException("Unsupported map-key type " + keyType);
}
final Function<DataQuery, Optional<?>> keyDeserializer;
final Optional<RegistryType<Object>> registryTypeForKey = SpongeDataManager.INSTANCE.findRegistryTypeFor((Class) keyType);
if (registryTypeForKey.isPresent()) {
keyDeserializer = key -> registryTypeForKey.flatMap(regType -> Sponge.game().findRegistry(regType)).flatMap(r -> r.findValue(ResourceKey.resolve(key.toString())));
} else if (((Class<?>) keyType).isEnum()) {
keyDeserializer = key -> Optional.ofNullable(Enum.valueOf(((Class<? extends Enum>) keyType), key.toString()));
} else if (keyType == String.class) {
keyDeserializer = key -> Optional.of(key.toString());
} else if (keyType == UUID.class) {
keyDeserializer = key -> Optional.of(UUID.fromString(key.toString()));
} else if (keyType == ResourceKey.class) {
keyDeserializer = key -> Optional.of(ResourceKey.resolve(key.toString()));
} else {
throw new UnsupportedOperationException("Unsupported map-key type " + keyType);
}
final BiFunction<DataView, DataQuery, Optional<Object>> valueDeserializer = this.getDeserializer(valueType);
return (view, dataQuery) -> (Optional<T>) view.getView(dataQuery).map(mapView -> {
final Map<Object, Object> resultMap = new HashMap<>();
for (final DataQuery key : mapView.keys(false)) {
final Object mapKey = keyDeserializer.apply(key).orElseThrow(() -> new UnsupportedOperationException("Key not found " + key + " as " + keyType));
final Optional<?> mapValue = valueDeserializer.apply(mapView, key);
resultMap.put(mapKey, mapValue.get());
}
return resultMap;
});
}
return (view, dataQuery) -> (Optional<T>) view.get(dataQuery);
}
use of org.spongepowered.api.ResourceKey in project SpongeCommon by SpongePowered.
the class MobSpawnerData method setEntities.
private static void setEntities(final BaseSpawnerAccessor logic, final WeightedTable<EntityArchetype> table) {
logic.accessor$spawnPotentials().clear();
for (final TableEntry<EntityArchetype> entry : table) {
if (!(entry instanceof WeightedObject)) {
continue;
}
final WeightedObject<EntityArchetype> object = (WeightedObject<EntityArchetype>) entry;
final CompoundTag compound = NBTTranslator.INSTANCE.translate(object.get().entityData());
if (!compound.contains(Constants.Entity.ENTITY_TYPE_ID)) {
final ResourceKey key = (ResourceKey) (Object) net.minecraft.world.entity.EntityType.getKey((net.minecraft.world.entity.EntityType<?>) object.get().type());
compound.putString(Constants.Entity.ENTITY_TYPE_ID, key.toString());
}
logic.accessor$spawnPotentials().add(new SpawnData((int) entry.weight(), compound));
}
}
use of org.spongepowered.api.ResourceKey in project SpongeCommon by SpongePowered.
the class MobSpawnerData method setNextEntity.
private static void setNextEntity(final BaseSpawner logic, final WeightedSerializableObject<EntityArchetype> value) {
final CompoundTag compound = NBTTranslator.INSTANCE.translate(value.get().entityData());
if (!compound.contains(Constants.Entity.ENTITY_TYPE_ID)) {
final ResourceKey key = (ResourceKey) (Object) net.minecraft.world.entity.EntityType.getKey((net.minecraft.world.entity.EntityType<?>) value.get().type());
compound.putString(Constants.Entity.ENTITY_TYPE_ID, key.toString());
}
logic.setNextSpawnData(new SpawnData((int) value.weight(), compound));
}
use of org.spongepowered.api.ResourceKey in project SpongeCommon by SpongePowered.
the class AbstractMinecartData method register.
// @formatter:off
public static void register(final DataProviderRegistrator registrator) {
registrator.asMutable(AbstractMinecart.class).create(Keys.BLOCK_STATE).get(h -> h.hasCustomDisplay() ? (BlockState) h.getDisplayBlockState() : null).set((h, v) -> h.setDisplayBlockState((net.minecraft.world.level.block.state.BlockState) v)).delete(h -> h.setCustomDisplay(false)).create(Keys.IS_ON_RAIL).get(h -> {
final BlockPos pos = h.blockPosition();
if (h.level.getBlockState(pos).is(BlockTags.RAILS)) {
return true;
}
final BlockPos posBelow = pos.offset(0, -1, 0);
return h.level.getBlockState(posBelow).is(BlockTags.RAILS);
}).create(Keys.MINECART_BLOCK_OFFSET).get(AbstractMinecart::getDisplayOffset).setAnd(AbstractMinecartData::setBlockOffset).deleteAnd(h -> AbstractMinecartData.setBlockOffset(h, h.getDefaultDisplayOffset())).asMutable(AbstractMinecartBridge.class).create(Keys.AIRBORNE_VELOCITY_MODIFIER).get(AbstractMinecartBridge::bridge$getAirborneMod).set(AbstractMinecartBridge::bridge$setAirborneMod).create(Keys.SLOWS_UNOCCUPIED).get(AbstractMinecartBridge::bridge$getSlowWhenEmpty).set(AbstractMinecartBridge::bridge$setSlowWhenEmpty).create(Keys.DERAILED_VELOCITY_MODIFIER).get(AbstractMinecartBridge::bridge$getDerailedMod).set(AbstractMinecartBridge::bridge$setDerailedMod).create(Keys.POTENTIAL_MAX_SPEED).get(AbstractMinecartBridge::bridge$getMaxSpeed).set(AbstractMinecartBridge::bridge$setMaxSpeed);
final ResourceKey minecartDataStoreKey = ResourceKey.sponge("minecart");
registrator.spongeDataStore(minecartDataStoreKey, 2, new DataContentUpdater[] { AbstractMinecartData.MINECART_UPDATER_BYTE_TO_BOOL_FIX }, AbstractMinecartBridge.class, Keys.POTENTIAL_MAX_SPEED, Keys.SLOWS_UNOCCUPIED, Keys.AIRBORNE_VELOCITY_MODIFIER, Keys.DERAILED_VELOCITY_MODIFIER);
SpongeDataManager.INSTANCE.registerLegacySpongeData(Constants.Entity.Minecart.MAX_SPEED, minecartDataStoreKey, Keys.POTENTIAL_MAX_SPEED);
SpongeDataManager.INSTANCE.registerLegacySpongeData(Constants.Entity.Minecart.SLOW_WHEN_EMPTY, minecartDataStoreKey, Keys.SLOWS_UNOCCUPIED);
SpongeDataManager.INSTANCE.registerLegacySpongeData(Constants.Entity.Minecart.AIRBORNE_MODIFIER, minecartDataStoreKey, Keys.AIRBORNE_VELOCITY_MODIFIER);
SpongeDataManager.INSTANCE.registerLegacySpongeData(Constants.Entity.Minecart.DERAILED_MODIFIER, minecartDataStoreKey, Keys.DERAILED_VELOCITY_MODIFIER);
}
use of org.spongepowered.api.ResourceKey in project SpongeCommon by SpongePowered.
the class SpongeCommand method reloadWorldExecutor.
@NonNull
private CommandResult reloadWorldExecutor(final CommandContext context) {
final ServerWorld target = context.requireOne(this.worldKey);
final ResourceKey worldId = target.key();
SpongeGameConfigs.getForWorld(target).reload().whenComplete(($, error) -> {
if (error != null) {
context.sendMessage(Identity.nil(), Component.text(b -> b.content("Failed to reload configuration for world ").append(Component.text(worldId.toString(), Style.style(TextDecoration.BOLD))).append(Component.text(". See the console for details.")).color(NamedTextColor.RED)));
SpongeCommon.logger().error("Failed to reload configuration of world '{}'", worldId, error);
} else {
context.sendMessage(Identity.nil(), Component.text("Successfully reloaded configuration for world ", NamedTextColor.GREEN).append(Component.text(worldId.toString(), Style.style(TextDecoration.BOLD))).append(Component.text("!")));
}
});
return CommandResult.success();
}
Aggregations