Search in sources :

Example 1 with CatalogType

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

the class SpongeGameRegistry method preRegistryInit.

public void preRegistryInit() {
    CommonModuleRegistry.getInstance().registerDefaultModules();
    final DirectedGraph<Class<? extends RegistryModule>> graph = new DirectedGraph<>();
    for (RegistryModule module : this.registryModules) {
        this.classMap.put(module.getClass(), module);
        addToGraph(module, graph);
    }
    // Now we need ot do the catalog ones
    for (CatalogRegistryModule<?> module : this.catalogRegistryMap.values()) {
        this.classMap.put(module.getClass(), module);
        addToGraph(module, graph);
    }
    try {
        this.orderedModules.addAll(TopologicalOrder.createOrderedLoad(graph));
    } catch (CyclicGraphException e) {
        StringBuilder msg = new StringBuilder();
        msg.append("Registry module dependencies are cyclical!\n");
        msg.append("Dependency loops are:\n");
        for (DataNode<?>[] cycle : e.getCycles()) {
            msg.append("[");
            for (DataNode<?> node : cycle) {
                msg.append(node.getData().toString()).append(" ");
            }
            msg.append("]\n");
        }
        SpongeImpl.getLogger().fatal(msg.toString());
        throw new RuntimeException("Registry modules dependencies error.");
    }
    registerModulePhase();
    SpongeVillagerRegistry.registerVanillaTrades();
    DataRegistrar.setupSerialization();
    final List<Tuple<Class<? extends CatalogType>, CatalogRegistryModule<?>>> modules = new ArrayList<>();
    for (Map.Entry<Class<? extends CatalogType>, CatalogRegistryModule<?>> entry : this.catalogRegistryMap.entrySet()) {
        modules.add(new Tuple<>(entry.getKey(), entry.getValue()));
    }
    modules.sort(Comparator.comparing(tuple -> tuple.getFirst().getSimpleName()));
    if (PRINT_CATALOG_TYPES) {
        // Lol... this gets spammy really fast.... Probably at some point should be put to file.
        final PrettyPrinter printer = new PrettyPrinter(100).add("Printing all Catalogs and their ID's").centre().hr().addWrapped("This is a test to print out all registered catalogs during initialization for their mapping, id's, and objects themselves.");
        for (Tuple<Class<? extends CatalogType>, CatalogRegistryModule<?>> module : modules) {
            printer.add(" %s : %s", "CatalogType", module.getFirst().getSimpleName());
            final Collection<? extends CatalogType> all = module.getSecond().getAll();
            final List<CatalogType> catalogTypes = new ArrayList<>(all);
            catalogTypes.sort(Comparator.comparing(CatalogType::getId));
            for (CatalogType catalogType : catalogTypes) {
                printer.add("  -%s", catalogType.getId());
            }
            printer.hr();
        }
        printer.trace(System.err, SpongeImpl.getLogger(), Level.DEBUG);
    }
}
Also used : DataNode(org.spongepowered.common.util.graph.DirectedGraph.DataNode) ValueFactory(org.spongepowered.api.data.value.ValueFactory) BlockStatistic(org.spongepowered.api.statistic.BlockStatistic) TextSerializerFactory(org.spongepowered.api.text.serializer.TextSerializerFactory) Level(org.apache.logging.log4j.Level) FurnaceRecipes(net.minecraft.item.crafting.FurnaceRecipes) CyclicGraphException(org.spongepowered.common.util.graph.CyclicGraphException) BookView(org.spongepowered.api.text.BookView) ExtentBufferFactory(org.spongepowered.api.world.extent.ExtentBufferFactory) Block(net.minecraft.block.Block) TextColor(org.spongepowered.api.text.format.TextColor) RegistryModuleAlreadyRegisteredException(org.spongepowered.api.registry.RegistryModuleAlreadyRegisteredException) SpongeSelectorFactory(org.spongepowered.common.text.selector.SpongeSelectorFactory) Map(java.util.Map) Path(java.nio.file.Path) SpongeTextSerializerFactory(org.spongepowered.common.text.serializer.SpongeTextSerializerFactory) ItemStatistic(org.spongepowered.api.statistic.ItemStatistic) EntityList(net.minecraft.entity.EntityList) DisplaySlotRegistryModule(org.spongepowered.common.registry.type.scoreboard.DisplaySlotRegistryModule) AITaskTypeModule(org.spongepowered.common.registry.type.entity.AITaskTypeModule) RegistryModuleLoader(org.spongepowered.common.registry.util.RegistryModuleLoader) Set(java.util.Set) DisplaySlot(org.spongepowered.api.scoreboard.displayslot.DisplaySlot) DirectedGraph(org.spongepowered.common.util.graph.DirectedGraph) AITaskType(org.spongepowered.api.entity.ai.task.AITaskType) Favicon(org.spongepowered.api.network.status.Favicon) Singleton(com.google.inject.Singleton) DataRegistration(org.spongepowered.api.data.DataRegistration) Agent(org.spongepowered.api.entity.living.Agent) PrettyPrinter(org.spongepowered.asm.util.PrettyPrinter) Supplier(java.util.function.Supplier) SpongeDataManager(org.spongepowered.common.data.SpongeDataManager) ArrayList(java.util.ArrayList) AdditionalCatalogRegistryModule(org.spongepowered.api.registry.AdditionalCatalogRegistryModule) Rotation(org.spongepowered.api.util.rotation.Rotation) Text(org.spongepowered.api.text.Text) SmeltingRecipeRegistry(org.spongepowered.api.item.recipe.smelting.SmeltingRecipeRegistry) TopologicalOrder(org.spongepowered.common.util.graph.TopologicalOrder) Nullable(javax.annotation.Nullable) StatList(net.minecraft.stats.StatList) CraftingRecipeRegistry(org.spongepowered.api.item.recipe.crafting.CraftingRecipeRegistry) IOException(java.io.IOException) Field(java.lang.reflect.Field) EntityStatistic(org.spongepowered.api.statistic.EntityStatistic) SpongeTranslation(org.spongepowered.common.text.translation.SpongeTranslation) AbstractAITask(org.spongepowered.api.entity.ai.task.AbstractAITask) ResettableBuilder(org.spongepowered.api.util.ResettableBuilder) TypeSerializers(ninja.leaping.configurate.objectmapping.serialize.TypeSerializers) ResourceLocation(net.minecraft.util.ResourceLocation) RegistryModule(org.spongepowered.api.registry.RegistryModule) PluginProvidedRegistryModule(org.spongepowered.api.registry.util.PluginProvidedRegistryModule) SpongePropertyRegistry(org.spongepowered.common.data.property.SpongePropertyRegistry) Item(net.minecraft.item.Item) ExtraClassCatalogRegistryModule(org.spongepowered.api.registry.ExtraClassCatalogRegistryModule) URL(java.net.URL) Inject(com.google.inject.Inject) DefaultGameRules(org.spongepowered.api.world.gamerule.DefaultGameRules) LocaleCache(org.spongepowered.common.util.LocaleCache) GameRegistry(org.spongepowered.api.GameRegistry) CatalogRegistryModule(org.spongepowered.api.registry.CatalogRegistryModule) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) RotationRegistryModule(org.spongepowered.common.registry.type.block.RotationRegistryModule) Locale(java.util.Locale) RegistrationDependency(org.spongepowered.api.registry.util.RegistrationDependency) StatisticTypes(org.spongepowered.api.statistic.StatisticTypes) BookViewDataBuilder(org.spongepowered.api.text.serializer.BookViewDataBuilder) IdentityHashMap(java.util.IdentityHashMap) BufferedImage(java.awt.image.BufferedImage) Collection(java.util.Collection) RegistrationPhase(org.spongepowered.api.registry.RegistrationPhase) CatalogType(org.spongepowered.api.CatalogType) Sponge(org.spongepowered.api.Sponge) ResourcePack(org.spongepowered.api.resourcepack.ResourcePack) Tuple(org.spongepowered.api.util.Tuple) SpongeFavicon(org.spongepowered.common.network.status.SpongeFavicon) SetSerializer(org.spongepowered.common.util.SetSerializer) SpongeGameRegistryRegisterEvent(org.spongepowered.common.event.registry.SpongeGameRegistryRegisterEvent) Cause(org.spongepowered.api.event.cause.Cause) List(java.util.List) BlockType(org.spongepowered.api.block.BlockType) Optional(java.util.Optional) EventContext(org.spongepowered.api.event.cause.EventContext) SpongeImpl(org.spongepowered.common.SpongeImpl) CatalogTypeTypeSerializer(org.spongepowered.common.config.CatalogTypeTypeSerializer) TextTemplate(org.spongepowered.api.text.TextTemplate) SpongeCraftingRecipeRegistry(org.spongepowered.common.item.recipe.crafting.SpongeCraftingRecipeRegistry) TypeToken(com.google.common.reflect.TypeToken) HashSet(java.util.HashSet) ImmutableList(com.google.common.collect.ImmutableList) TextConfigSerializer(org.spongepowered.api.text.serializer.TextConfigSerializer) VillagerRegistry(org.spongepowered.api.item.merchant.VillagerRegistry) DataRegistrar(org.spongepowered.common.data.DataRegistrar) Translation(org.spongepowered.api.text.translation.Translation) TextTemplateConfigSerializer(org.spongepowered.api.text.serializer.TextTemplateConfigSerializer) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) SpongeExtentBufferFactory(org.spongepowered.common.world.extent.SpongeExtentBufferFactory) StatisticType(org.spongepowered.api.statistic.StatisticType) SpongeValueFactory(org.spongepowered.common.data.value.SpongeValueFactory) EntityType(org.spongepowered.api.entity.EntityType) Comparator(java.util.Comparator) ItemType(org.spongepowered.api.item.ItemType) Collections(java.util.Collections) InputStream(java.io.InputStream) DisplaySlotRegistryModule(org.spongepowered.common.registry.type.scoreboard.DisplaySlotRegistryModule) AdditionalCatalogRegistryModule(org.spongepowered.api.registry.AdditionalCatalogRegistryModule) RegistryModule(org.spongepowered.api.registry.RegistryModule) PluginProvidedRegistryModule(org.spongepowered.api.registry.util.PluginProvidedRegistryModule) ExtraClassCatalogRegistryModule(org.spongepowered.api.registry.ExtraClassCatalogRegistryModule) CatalogRegistryModule(org.spongepowered.api.registry.CatalogRegistryModule) RotationRegistryModule(org.spongepowered.common.registry.type.block.RotationRegistryModule) ArrayList(java.util.ArrayList) CyclicGraphException(org.spongepowered.common.util.graph.CyclicGraphException) 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) DirectedGraph(org.spongepowered.common.util.graph.DirectedGraph) DataNode(org.spongepowered.common.util.graph.DirectedGraph.DataNode) Map(java.util.Map) IdentityHashMap(java.util.IdentityHashMap) Tuple(org.spongepowered.api.util.Tuple)

Example 2 with CatalogType

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

the class SpongeHooks method getFriendlyCauseName.

public static String getFriendlyCauseName(Cause cause) {
    String causedBy = "Unknown";
    Object rootCause = cause.root();
    if (rootCause instanceof User) {
        User user = (User) rootCause;
        causedBy = user.getName();
    } else if (rootCause instanceof EntityItem) {
        EntityItem item = (EntityItem) rootCause;
        causedBy = item.getItem().getDisplayName();
    } else if (rootCause instanceof Entity) {
        Entity causeEntity = (Entity) rootCause;
        causedBy = causeEntity.getName();
    } else if (rootCause instanceof BlockSnapshot) {
        BlockSnapshot snapshot = (BlockSnapshot) rootCause;
        causedBy = snapshot.getState().getType().getId();
    } else if (rootCause instanceof CatalogType) {
        CatalogType type = (CatalogType) rootCause;
        causedBy = type.getId();
    } else if (rootCause instanceof PluginContainer) {
        PluginContainer plugin = (PluginContainer) rootCause;
        causedBy = plugin.getId();
    } else {
        causedBy = rootCause.getClass().getName();
    }
    return causedBy;
}
Also used : Entity(net.minecraft.entity.Entity) TileEntity(net.minecraft.tileentity.TileEntity) CatalogType(org.spongepowered.api.CatalogType) User(org.spongepowered.api.entity.living.player.User) PluginContainer(org.spongepowered.api.plugin.PluginContainer) BlockSnapshot(org.spongepowered.api.block.BlockSnapshot) EntityItem(net.minecraft.entity.item.EntityItem)

Example 3 with CatalogType

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

the class CatalogTypeClassesTest method testCatalogFieldExists.

@Test
public void testCatalogFieldExists() throws Exception {
    try {
        final CatalogType o = (CatalogType) this.targetedField.get(null);
        // Validates that the field is not a dummy object. If it is, it will throw an exception.
        o.getId();
    } catch (Exception e) {
        this.isDummy = true;
        throw e;
    }
}
Also used : CatalogType(org.spongepowered.api.CatalogType) RegistryException(org.spongepowered.api.registry.RegistryException) Test(org.junit.Test)

Example 4 with CatalogType

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

the class MemoryDataView method setCollection.

@SuppressWarnings({ "unchecked", "rawtypes" })
private void setCollection(String key, Collection<?> value) {
    final ImmutableList.Builder<Object> builder = ImmutableList.builder();
    final LanternDataManager manager = getDataManager();
    for (Object object : value) {
        if (object instanceof DataSerializable) {
            builder.add(((DataSerializable) object).toContainer());
        } else if (object instanceof DataView) {
            if (this.safety == SafetyMode.ALL_DATA_CLONED || this.safety == SafetyMode.CLONED_ON_SET) {
                final MemoryDataView view = new MemoryDataContainer(this.safety);
                final DataView internalView = (DataView) object;
                for (Map.Entry<DataQuery, Object> entry : internalView.getValues(false).entrySet()) {
                    view.set(entry.getKey(), entry.getValue());
                }
                builder.add(view);
            } else {
                builder.add(object);
            }
        } else if (object instanceof CatalogType) {
            builder.add(((CatalogType) object).getId());
        } else if (object instanceof Map) {
            builder.add(ensureSerialization((Map) object));
        } else if (object instanceof Collection) {
            builder.add(ensureSerialization((Collection) object));
        } else {
            final TypeToken<?> typeToken = TypeToken.of(object.getClass());
            final DataTypeSerializer serializer = manager == null ? null : manager.getTypeSerializer(typeToken).orElse(null);
            if (serializer != null) {
                final Object result = serializer.serialize(typeToken, manager.getTypeSerializerContext(), object);
                checkArgument(!result.equals(this), "Cannot insert self-referencing Objects!");
                builder.add(result);
            } else {
                builder.add(object);
            }
        }
    }
    this.map.put(key, builder.build());
}
Also used : ImmutableList(com.google.common.collect.ImmutableList) DataSerializable(org.spongepowered.api.data.DataSerializable) DataView(org.spongepowered.api.data.DataView) CatalogType(org.spongepowered.api.CatalogType) Collection(java.util.Collection) DataTypeSerializer(org.lanternpowered.server.data.persistence.DataTypeSerializer) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 5 with CatalogType

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

the class MemoryDataView method set.

@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public DataView set(DataQuery path, Object value) {
    checkNotNull(path, "path");
    checkNotNull(value, "value");
    final LanternDataManager manager = getDataManager();
    final List<String> parts = path.getParts();
    final String key = parts.get(0);
    if (parts.size() > 1) {
        final DataQuery subQuery = of(key);
        final Optional<DataView> subViewOptional = getUnsafeView(subQuery);
        final DataView subView;
        if (!subViewOptional.isPresent()) {
            createView(subQuery);
            subView = (DataView) this.map.get(key);
        } else {
            subView = subViewOptional.get();
        }
        subView.set(path.popFirst(), value);
        return this;
    }
    Optional<DataTypeSerializer> optDataTypeSerializer;
    TypeToken typeToken;
    if (value instanceof DataView) {
        checkArgument(value != this, "Cannot set a DataView to itself.");
        // always have to copy a data view to avoid overwriting existing
        // views and to set the interior path correctly.
        copyDataView(path, (DataView) value);
    } else if (value instanceof DataSerializable) {
        final DataContainer valueContainer = ((DataSerializable) value).toContainer();
        checkArgument(!(valueContainer).equals(this), "Cannot insert self-referencing DataSerializable");
        // see above for why this is copied
        copyDataView(path, valueContainer);
    } else if (value instanceof CatalogType) {
        return set(path, ((CatalogType) value).getId());
    } else if (value instanceof Integer || value instanceof Byte || value instanceof Short || value instanceof Float || value instanceof Double || value instanceof Long || value instanceof String || value instanceof Character || value instanceof Boolean) {
        this.map.put(key, value);
        return this;
    } else if (manager != null && (optDataTypeSerializer = manager.getTypeSerializer(typeToken = TypeToken.of(value.getClass()))).isPresent()) {
        final DataTypeSerializer serializer = optDataTypeSerializer.get();
        final Object serialized = serializer.serialize(typeToken, manager.getTypeSerializerContext(), value);
        if (serialized instanceof DataContainer) {
            final DataContainer container = (DataContainer) serialized;
            checkArgument(!container.equals(this), "Cannot insert self-referencing Objects!");
            // see above for why this is copied
            copyDataView(path, container);
        } else {
            this.map.put(key, serialized);
        }
    } else if (value instanceof Collection) {
        setCollection(key, (Collection) value);
    } else if (value instanceof Map) {
        setMap(key, (Map) value);
    } else if (value.getClass().isArray()) {
        if (this.safety == SafetyMode.ALL_DATA_CLONED || this.safety == SafetyMode.CLONED_ON_SET) {
            if (value instanceof byte[]) {
                this.map.put(key, ArrayUtils.clone((byte[]) value));
            } else if (value instanceof short[]) {
                this.map.put(key, ArrayUtils.clone((short[]) value));
            } else if (value instanceof int[]) {
                this.map.put(key, ArrayUtils.clone((int[]) value));
            } else if (value instanceof long[]) {
                this.map.put(key, ArrayUtils.clone((long[]) value));
            } else if (value instanceof float[]) {
                this.map.put(key, ArrayUtils.clone((float[]) value));
            } else if (value instanceof double[]) {
                this.map.put(key, ArrayUtils.clone((double[]) value));
            } else if (value instanceof boolean[]) {
                this.map.put(key, ArrayUtils.clone((boolean[]) value));
            } else {
                this.map.put(key, ArrayUtils.clone((Object[]) value));
            }
        } else {
            this.map.put(key, value);
        }
    } else {
        this.map.put(key, value);
    }
    return this;
}
Also used : DataSerializable(org.spongepowered.api.data.DataSerializable) DataContainer(org.spongepowered.api.data.DataContainer) DataQuery(org.spongepowered.api.data.DataQuery) DataView(org.spongepowered.api.data.DataView) CatalogType(org.spongepowered.api.CatalogType) TypeToken(com.google.common.reflect.TypeToken) Collection(java.util.Collection) DataTypeSerializer(org.lanternpowered.server.data.persistence.DataTypeSerializer) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap)

Aggregations

CatalogType (org.spongepowered.api.CatalogType)22 Map (java.util.Map)9 ItemDataNode (io.github.nucleuspowered.nucleus.configurate.datatypes.ItemDataNode)7 ArrayList (java.util.ArrayList)7 List (java.util.List)4 Optional (java.util.Optional)4 Sponge (org.spongepowered.api.Sponge)4 DataView (org.spongepowered.api.data.DataView)4 CatalogRegistryModule (org.spongepowered.api.registry.CatalogRegistryModule)4 Text (org.spongepowered.api.text.Text)4 IOException (java.io.IOException)3 Method (java.lang.reflect.Method)3 Collection (java.util.Collection)3 IdentityHashMap (java.util.IdentityHashMap)3 BlockState (org.spongepowered.api.block.BlockState)3 ItemType (org.spongepowered.api.item.ItemType)3 ItemStack (org.spongepowered.api.item.inventory.ItemStack)3 Preconditions.checkNotNull (com.google.common.base.Preconditions.checkNotNull)2 ImmutableList (com.google.common.collect.ImmutableList)2 ImmutableMap (com.google.common.collect.ImmutableMap)2