Search in sources :

Example 16 with CatalogType

use of org.spongepowered.api.CatalogType in project SpongeCommon by SpongePowered.

the class SpongeGameRegistry method throwRegistryEvent.

@SuppressWarnings("unchecked")
private void throwRegistryEvent(RegistryModule module) {
    if (this.phase == RegistrationPhase.INIT && module instanceof AdditionalCatalogRegistryModule && (!(module instanceof SpongeAdditionalCatalogRegistryModule) || ((SpongeAdditionalCatalogRegistryModule) module).allowsApiRegistration()) && module.getClass().getAnnotation(CustomRegistrationPhase.class) == null) {
        Class<? extends CatalogType> catalogClass = null;
        for (Map.Entry<Class<? extends CatalogType>, CatalogRegistryModule<?>> entry : this.catalogRegistryMap.entrySet()) {
            if (entry.getValue() == module) {
                catalogClass = entry.getKey();
            }
        }
        if (catalogClass == null) {
            // This isn't a valid registered registry
            // We should throw an exception or print out an exception, but otherwise, not going to bother at this moment.
            new PrettyPrinter(60).centre().add("Unregistered RegistryModule").hr().addWrapped(60, "An unknown registry module was added to the ordered set of modules, but the " + "module itself is not registered with the GameRegistry!").add().add("%s : %s", "Registry Module", module.toString()).add().add(new Exception()).add().add("To fix this, the developer providing the module needs to register the module correctly.").trace();
            return;
        }
        final AdditionalCatalogRegistryModule registryModule = (AdditionalCatalogRegistryModule) module;
        SpongeImpl.postEvent(new SpongeGameRegistryRegisterEvent(Sponge.getCauseStackManager().getCurrentCause(), catalogClass, registryModule));
    }
}
Also used : CatalogType(org.spongepowered.api.CatalogType) PrettyPrinter(org.spongepowered.asm.util.PrettyPrinter) AdditionalCatalogRegistryModule(org.spongepowered.api.registry.AdditionalCatalogRegistryModule) ExtraClassCatalogRegistryModule(org.spongepowered.api.registry.ExtraClassCatalogRegistryModule) CatalogRegistryModule(org.spongepowered.api.registry.CatalogRegistryModule) AdditionalCatalogRegistryModule(org.spongepowered.api.registry.AdditionalCatalogRegistryModule) SpongeGameRegistryRegisterEvent(org.spongepowered.common.event.registry.SpongeGameRegistryRegisterEvent) Map(java.util.Map) IdentityHashMap(java.util.IdentityHashMap) CyclicGraphException(org.spongepowered.common.util.graph.CyclicGraphException) RegistryModuleAlreadyRegisteredException(org.spongepowered.api.registry.RegistryModuleAlreadyRegisteredException) IOException(java.io.IOException)

Example 17 with CatalogType

use of org.spongepowered.api.CatalogType in project LanternServer by LanternPowered.

the class CatalogTypeTypeAdapterFactory method create.

@Nullable
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    final Class<? super T> raw = type.getRawType();
    if (!CatalogType.class.isAssignableFrom(raw)) {
        return null;
    }
    final TypeAdapter<JsonElement> jsonElementTypeAdapter = gson.getAdapter(JsonElement.class);
    return new TypeAdapter<T>() {

        @Override
        public void write(JsonWriter out, T value) throws IOException {
            jsonElementTypeAdapter.write(out, new JsonPrimitive(((CatalogType) value).getId()));
        }

        @Override
        public T read(JsonReader in) throws IOException {
            final String id = jsonElementTypeAdapter.read(in).getAsString();
            // noinspection unchecked
            return (T) Sponge.getRegistry().getType((Class<? extends CatalogType>) raw, id).orElseThrow(() -> new IllegalArgumentException("There does not exist a " + raw.getName() + " with id: " + id));
        }
    };
}
Also used : CatalogType(org.spongepowered.api.CatalogType) JsonPrimitive(com.google.gson.JsonPrimitive) JsonElement(com.google.gson.JsonElement) TypeAdapter(com.google.gson.TypeAdapter) JsonReader(com.google.gson.stream.JsonReader) JsonWriter(com.google.gson.stream.JsonWriter) Nullable(javax.annotation.Nullable)

Example 18 with CatalogType

use of org.spongepowered.api.CatalogType in project LanternServer by LanternPowered.

the class LanternWorldPropertiesIO method convert.

static LevelData convert(LanternWorldProperties properties, @Nullable Integer dimensionId, @Nullable BitSet dimensionMap) {
    final DataContainer rootContainer = DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED);
    final DataView dataView = rootContainer.createView(DATA);
    final DataContainer spongeRootContainer = properties.getAdditionalProperties().copy();
    final DataView spongeContainer = spongeRootContainer.createView(DataQueries.SPONGE_DATA);
    final DataView lanternDataView = spongeContainer.createView(LANTERN);
    dataView.set(SEED, properties.getSeed());
    dataView.set(VERSION, CURRENT_VERSION);
    final DataView rulesView = dataView.createView(GAME_RULES);
    for (Entry<String, String> en : properties.getGameRules().entrySet()) {
        rulesView.set(DataQuery.of(en.getKey()), en.getValue());
    }
    // Weather
    final WeatherData weatherData = properties.getWeatherData();
    final boolean raining = properties.isRaining();
    final boolean thunderStorm = properties.isThundering();
    dataView.set(RAINING, (byte) (properties.isRaining() ? 1 : 0));
    dataView.set(RAIN_TIME, properties.getRainTime());
    dataView.set(THUNDERING, (byte) (properties.isThundering() ? 1 : 0));
    dataView.set(THUNDER_TIME, properties.getThunderTime());
    dataView.set(HARDCORE, (byte) (properties.isHardcore() ? 1 : 0));
    dataView.set(CLEAR_WEATHER_TIME, raining || thunderStorm ? 0 : weatherData.getRemainingDuration());
    final DataView weatherDataView = lanternDataView.createView(WEATHER);
    weatherDataView.set(WEATHER_TYPE, weatherData.getWeather().getId());
    weatherDataView.set(WEATHER_REMAINING_DURATION, weatherData.getRemainingDuration());
    weatherDataView.set(WEATHER_RUNNING_DURATION, weatherData.getRunningDuration());
    // Time
    final TimeData timeData = properties.getTimeData();
    dataView.set(TIME, timeData.getDayTime());
    dataView.set(AGE, timeData.getAge());
    lanternDataView.set(MOON_PHASE, timeData.getMoonPhase().toString().toLowerCase());
    dataView.set(LAST_PLAYED, properties.getLastPlayedTime());
    dataView.set(SIZE_ON_DISK, 0L);
    dataView.set(INITIALIZED, (byte) (properties.isInitialized() ? 1 : 0));
    String generatorId = properties.getGeneratorType().getId();
    if (generatorId.startsWith("minecraft:")) {
        generatorId = generatorId.replaceFirst("minecraft:", "");
    }
    dataView.set(GENERATOR_NAME, generatorId);
    // The default world generator has a version of one
    dataView.set(GENERATOR_VERSION, generatorId.equalsIgnoreCase("default") ? 1 : 0);
    // The flat world generator has a different settings format
    if (generatorId.equalsIgnoreCase("flat")) {
        dataView.set(GENERATOR_OPTIONS, properties.getGeneratorSettings().getString(AbstractFlatGeneratorType.SETTINGS).get());
        try {
            dataView.set(GENERATOR_OPTIONS_EXTRA, JsonDataFormat.writeAsString(properties.getGeneratorSettings().copy().remove(AbstractFlatGeneratorType.SETTINGS)));
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    } else {
        dataView.set(GENERATOR_OPTIONS, properties.getGeneratorSettings());
    }
    dataView.set(DIFFICULTY, ((LanternDifficulty) properties.getDifficulty()).getInternalId());
    dataView.set(DIFFICULTY_LOCKED, (byte) (properties.isDifficultyLocked() ? 1 : 0));
    dataView.set(GAME_MODE, ((LanternGameMode) properties.getGameMode()).getInternalId());
    dataView.set(MAP_FEATURES, (byte) (properties.mapFeatures ? 1 : 0));
    final LanternWorldBorder border = properties.getWorldBorder();
    dataView.set(BORDER_CENTER_X, border.centerX);
    dataView.set(BORDER_CENTER_Z, border.centerZ);
    dataView.set(BORDER_DAMAGE, border.damage);
    dataView.set(BORDER_DAMAGE_THRESHOLD, border.damageThreshold);
    dataView.set(BORDER_SIZE_END, border.diameterEnd);
    dataView.set(BORDER_SIZE_START, border.getDiameter());
    dataView.set(BORDER_SIZE_LERP_TIME, border.getTimeRemaining());
    dataView.set(BORDER_WARNING_BLOCKS, border.warningDistance);
    dataView.set(BORDER_WARNING_TIME, border.warningTime);
    final Vector3i spawn = properties.getSpawnPosition();
    dataView.set(SPAWN_X, spawn.getX());
    dataView.set(SPAWN_Y, spawn.getY());
    dataView.set(SPAWN_Z, spawn.getZ());
    spongeContainer.set(GENERATE_BONUS_CHEST, (byte) (properties.doesGenerateBonusChest() ? 1 : 0));
    spongeContainer.set(DIMENSION_TYPE, properties.getDimensionType().getId());
    spongeContainer.set(PORTAL_AGENT_TYPE, properties.getPortalAgentType().getId());
    spongeContainer.set(GENERATOR_MODIFIERS, properties.generatorModifiers.stream().map(CatalogType::getId).collect(Collectors.toList()));
    // Serialization behavior
    short serializationBehaviorId = 1;
    if (properties.getSerializationBehavior() == SerializationBehaviors.MANUAL) {
        serializationBehaviorId = 0;
    } else if (properties.getSerializationBehavior() == SerializationBehaviors.NONE) {
        serializationBehaviorId = -1;
    }
    spongeContainer.set(SERIALIZATION_BEHAVIOR, serializationBehaviorId);
    // Tracker
    final List<DataView> trackerUniqueIdViews = new ArrayList<>();
    final List<UUID> uniqueIdsByIndex = properties.getTrackerIdAllocator().getUniqueIdsByIndex();
    for (UUID uniqueId : uniqueIdsByIndex) {
        final DataView uniqueIdView = DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED);
        if (uniqueId != null) {
            uniqueIdView.set(UUID_MOST, uniqueId.getMostSignificantBits());
            uniqueIdView.set(UUID_LEAST, uniqueId.getLeastSignificantBits());
        }
        trackerUniqueIdViews.add(uniqueIdView);
    }
    spongeContainer.set(TRACKER_UUID_TABLE, trackerUniqueIdViews);
    return new LevelData(properties.getWorldName(), properties.getUniqueId(), rootContainer, spongeRootContainer, dimensionId, dimensionMap);
}
Also used : ArrayList(java.util.ArrayList) IOException(java.io.IOException) DataView(org.spongepowered.api.data.DataView) DataContainer(org.spongepowered.api.data.DataContainer) CatalogType(org.spongepowered.api.CatalogType) Vector3i(com.flowpowered.math.vector.Vector3i) UUID(java.util.UUID)

Example 19 with CatalogType

use of org.spongepowered.api.CatalogType in project LanternServer by LanternPowered.

the class ItemStackStore method serializeValues.

@Override
public void serializeValues(LanternItemStack object, SimpleValueContainer valueContainer, DataView dataView) {
    final ItemTypeObjectSerializer serializer = this.itemTypeSerializers.get(object.getType());
    if (serializer != null) {
        serializer.serializeValues(object, valueContainer, dataView);
    }
    DataView displayView = null;
    final Optional<Text> optDisplayName = valueContainer.remove(Keys.DISPLAY_NAME);
    if (optDisplayName.isPresent()) {
        displayView = getOrCreateView(dataView, DISPLAY);
        final Text displayName = optDisplayName.get();
        if (displayName instanceof TranslatableText) {
            final TranslatableText name1 = (TranslatableText) displayName;
            // We can only do this for translatable text without any formatting
            if (name1.getArguments().isEmpty() && name1.getChildren().isEmpty() && name1.getStyle().isEmpty() && name1.getColor() == TextColors.NONE) {
                displayView.set(LOCALIZED_NAME, name1.getTranslation().getId());
            } else {
                displayView.set(NAME, LanternTexts.toLegacy(displayName));
            }
        } else {
            displayView.set(NAME, LanternTexts.toLegacy(displayName));
        }
    }
    final Optional<List<Text>> optLore = valueContainer.remove(Keys.ITEM_LORE);
    if (optLore.isPresent() && !optLore.get().isEmpty()) {
        if (displayView == null) {
            displayView = getOrCreateView(dataView, DISPLAY);
        }
        displayView.set(LORE, optLore.get().stream().map(LanternTexts::toLegacy).collect(Collectors.toList()));
    }
    if (valueContainer.remove(Keys.UNBREAKABLE).orElse(false)) {
        dataView.set(UNBREAKABLE, (byte) 1);
    }
    final Optional<Set<BlockType>> optBlockTypes = valueContainer.remove(Keys.BREAKABLE_BLOCK_TYPES);
    if (optBlockTypes.isPresent() && !optBlockTypes.get().isEmpty()) {
        dataView.set(CAN_DESTROY, optBlockTypes.get().stream().map(CatalogType::getId).collect(Collectors.toSet()));
    }
    valueContainer.remove(Keys.ITEM_ENCHANTMENTS).ifPresent(list -> serializeEnchantments(dataView, ENCHANTMENTS, list));
    valueContainer.remove(Keys.STORED_ENCHANTMENTS).ifPresent(list -> serializeEnchantments(dataView, STORED_ENCHANTMENTS, list));
    super.serializeValues(object, valueContainer, dataView);
}
Also used : TranslatableText(org.spongepowered.api.text.TranslatableText) DataView(org.spongepowered.api.data.DataView) CatalogType(org.spongepowered.api.CatalogType) Set(java.util.Set) HashSet(java.util.HashSet) LanternTexts(org.lanternpowered.server.text.LanternTexts) TranslatableText(org.spongepowered.api.text.TranslatableText) Text(org.spongepowered.api.text.Text) List(java.util.List) ArrayList(java.util.ArrayList)

Example 20 with CatalogType

use of org.spongepowered.api.CatalogType in project LanternServer by LanternPowered.

the class LanternArgumentType method getConverter.

@SuppressWarnings("unchecked")
private static <T> Function<String, T> getConverter(final Class<T> type, String converterKey) {
    if (!converters.containsKey(converterKey)) {
        try {
            final Method valueOf = type.getMethod("valueOf", String.class);
            converters.put(converterKey, LanternSelectorFactory.<String, T>methodAsFunction(valueOf, true));
        } catch (NoSuchMethodException ignored) {
            if (CatalogType.class.isAssignableFrom(type)) {
                Class<? extends CatalogType> type2 = type.asSubclass(CatalogType.class);
                converters.put(converterKey, input -> (T) Sponge.getRegistry().getType(type2, input).get());
            } else {
                throw new IllegalStateException("Can't convert " + type);
            }
        } catch (SecurityException e) {
            Lantern.getLogger().warn("There occurred a security exception", e);
        }
    }
    return (Function<String, T>) converters.get(converterKey);
}
Also used : Lantern(org.lanternpowered.server.game.Lantern) Map(java.util.Map) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) CatalogType(org.spongepowered.api.CatalogType) Sponge(org.spongepowered.api.Sponge) EntityType(org.spongepowered.api.entity.EntityType) HashMap(java.util.HashMap) ArgumentType(org.spongepowered.api.text.selector.ArgumentType) Method(java.lang.reflect.Method) Function(java.util.function.Function) Function(java.util.function.Function) CatalogType(org.spongepowered.api.CatalogType) Method(java.lang.reflect.Method)

Aggregations

CatalogType (org.spongepowered.api.CatalogType)26 Map (java.util.Map)12 ArrayList (java.util.ArrayList)8 ItemDataNode (io.github.nucleuspowered.nucleus.configurate.datatypes.ItemDataNode)7 DataView (org.spongepowered.api.data.DataView)6 Nullable (javax.annotation.Nullable)5 CatalogRegistryModule (org.spongepowered.api.registry.CatalogRegistryModule)5 ImmutableMap (com.google.common.collect.ImmutableMap)4 Collection (java.util.Collection)4 List (java.util.List)4 Optional (java.util.Optional)4 Sponge (org.spongepowered.api.Sponge)4 DataContainer (org.spongepowered.api.data.DataContainer)4 Text (org.spongepowered.api.text.Text)4 ImmutableList (com.google.common.collect.ImmutableList)3 IOException (java.io.IOException)3 Method (java.lang.reflect.Method)3 IdentityHashMap (java.util.IdentityHashMap)3 BlockState (org.spongepowered.api.block.BlockState)3 DataSerializable (org.spongepowered.api.data.DataSerializable)3