001package net.minecraftforge.client.model;
002
003import java.io.InputStream;
004import java.net.URL;
005import java.util.Collection;
006import java.util.Map;
007
008import net.minecraftforge.client.model.obj.ObjModelLoader;
009
010import com.google.common.collect.Maps;
011
012import cpw.mods.fml.common.FMLLog;
013import cpw.mods.fml.relauncher.Side;
014import cpw.mods.fml.relauncher.SideOnly;
015
016/**
017 * Common interface for advanced model loading from files, based on file suffix
018 * Model support can be queried through the {@link #getSupportedSuffixes()} method.
019 * Instances can be created by calling {@link #loadModel(String)} with a class-loadable-path
020 *
021 * @author cpw
022 *
023 */
024@SideOnly(Side.CLIENT)
025public class AdvancedModelLoader {
026    private static Map<String, IModelCustomLoader> instances = Maps.newHashMap();
027
028    /**
029     * Register a new model handler
030     * @param modelHandler The model handler to register
031     */
032    public static void registerModelHandler(IModelCustomLoader modelHandler)
033    {
034        for (String suffix : modelHandler.getSuffixes())
035        {
036            instances.put(suffix, modelHandler);
037        }
038    }
039
040    /**
041     * Load the model from the supplied classpath resolvable resource name
042     * @param resourceName The resource name
043     * @return A model
044     * @throws IllegalArgumentException if the resource name cannot be understood
045     * @throws ModelFormatException if the underlying model handler cannot parse the model format
046     */
047    public static IModelCustom loadModel(String resourceName) throws IllegalArgumentException, ModelFormatException
048    {
049        int i = resourceName.lastIndexOf('.');
050        if (i == -1)
051        {
052            FMLLog.severe("The resource name %s is not valid", resourceName);
053            throw new IllegalArgumentException("The resource name is not valid");
054        }
055        String suffix = resourceName.substring(i);
056        IModelCustomLoader loader = instances.get(suffix);
057        if (loader == null)
058        {
059            FMLLog.severe("The resource name %s is not supported", resourceName);
060            throw new IllegalArgumentException("The resource name is not supported");
061        }
062
063        URL resource = AdvancedModelLoader.class.getResource(resourceName);
064        if (resource == null)
065        {
066            FMLLog.severe("The resource name %s could not be found", resourceName);
067            throw new IllegalArgumentException("The resource name could not be found");
068        }
069        return loader.loadInstance(resourceName, resource);
070    }
071
072    public static Collection<String> getSupportedSuffixes()
073    {
074        return instances.keySet();
075    }
076
077
078    static
079    {
080        registerModelHandler(new ObjModelLoader());
081    }
082}